反应:Spring 过渡行为不正常

React: Spring transition not behaving properly

我最近开始使用 React 和 JavaScript。我一直在阅读 Transition 组件的 Spring API 文档,并在进行一些测试时以这段代码结束。现在,我希望顺利过渡,但得到以下顺序:

对于我在文档中阅读的内容,我看不到我在此处做错了什么,因此非常欢迎任何帮助。我已经测试了不同的配置并且总是得到那个序列。

PS: 内容只是一个普通的 div,以其背景颜色为道具,所以没有什么特别的。

import React from 'react';
import './App.css';
import Content from './components/content';
import {Transition, config} from 'react-spring/renderprops';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      switch: false
    };
  }

  render() {
    return (
      <div id="container" onClick={() => {this.setState({switch: !this.state.switch})}}>
        <Transition
        config={config.slow}
        items={this.state.switch}
        from={{opacity: 0}}
        enter={{opacity: 1}}
        leave={{opacity: 0}}>
        {s => s ? () => <Content backgroundColor="rgb(37, 95, 142)"></Content>
                : () => <Content backgroundColor="rgb(37, 142, 118)"></Content>}
        </Transition>
      </div>
    );
  }
}

export default App;

谢谢!

Transition 改变了示例中的不透明度,但您从未将更改后的值提供给呈现的组件。它缺少箭头函数中的 prop 参数。您应该将此道具添加到组件的样式 属性。

例如:

props => (<Content props={props} backgroundColor="rgb(37, 95, 142)" />)

组件是这样的:

const Content = ({ backgroundColor, props }) => (
  <animated.div style={{ backgroundColor, ...props }}>Content</animated.div>
);

现在您可以看到不透明度发生变化。

我这里也使用了animated.div,为了更好的性能,将原生属性添加到Transition中。

这是我的例子: https://codesandbox.io/s/ecstatic-wood-7p1ym?file=/src/App.js