首页 > 解决方案 > (React Native) 仅淡入 Text 组件一次

问题描述

我正在尝试创建一个简单的标记功能。用户输入一个单词,当提交时,文本淡入另一个组件。目前,我将所有文本输入值发送到状态数组中,然后在向数组中添加新值时重新渲染数组项。

问题:

每当新标签淡入时,每个标签都会发生淡入动画,并且动画在我不断输入时循环播放。

我想发生的事情:

每个标签都会淡入一次并保持可见。

到目前为止,这是我的代码:

状态

 state = {
    allTags: []
  };

零件

    class Tags extends React.Component {
      fadeIn = new Animated.Value(0);

      fadeInTag = () => {
        this.fadeIn.setValue(0);
        Animated.timing(this.fadeIn, {
          toValue: 1,
          duration: 600
        }).start();
      };

      render() {
        const animationStyles = {
          opacity: this.fadeIn
        };

        return (
          <View>
            {this.props.allTags.map(function(tag, i) {
              return (
                <Animated.Text
                  key={i}
                  style={[animationStyles, tagStyles.fadeStyle]}
                >
                  {tag}
                </Animated.Text>
              );
            }, this.fadeInTag())}
          </View>
        );
      }
    }

任何帮助,将不胜感激。谢谢!

标签: reactjsreact-native

解决方案


这里的问题是您Tags每次setStatefor都会重新渲染tags。您应该将其移动Animated.Text到单独的组件并使用PureComponentshouldComponentUpdate防止重新渲染更改它们的道具。


class FadeText extends PureComponent {
  fadeIn = new Animated.Value(0);

  componentDidMount(){
    Animated.timing(this.fadeIn, {
      toValue: 1,
      duration: 2000,
      useNativeDriver: true
    }).start();
  }

  render(){
    const {tag} = this.props;
    return (
      <Animated.Text style={{ opacity: this.fadeIn }}>
        {tag}
      </Animated.Text>
    );
  }
}

此处提供了一个示例


推荐阅读