首页 > 解决方案 > 如何在每个 onPress 事件(或状态更改)上淡入淡出?

问题描述

下面的组件在第一次显示时会淡出。当从 RadioInputWidget 触发 onPress 时,使用 CompetencyView 的控件会更改其状态,然后使用新的参数值更新 CompetencyView。这一切都很好。

我想要的是每次触发 onPress 时控件都会再次淡入。它是否与 onPress 被触发的事实直接相关,或者它是否是状态发生变化的直接结果对我来说并不重要,尽管我认为一种方法比另一种方法更好。不幸的是,我无法弄清楚如何让它工作。

const CompetencyView = ({ pageNumber, competencyName, question, skillText, scaleDescriptions, responseValue, onPress }) => {
  const fadeAnim = useRef(new Animated.Value(0)).current  // Initial value for opacity: 0

  React.useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true
    }).start();
  }, [fadeAnim])
  
  return (
    <LinearGradient style={{flex: 1}} colors={['#ff0000', '#ff492b', '#770000']}>
      <Animated.View style={{flex: 1, backgroundColor: 'red', opacity: fadeAnim  }}>
        <View style={competencyStyles.View}>
          <Text style={competencyStyles.Heading}>{competencyName}</Text>
          <Text style={competencyStyles.Question}>{question}</Text>
          <Text style={competencyStyles.SkillText}>{skillText}</Text>
          <RadioInputWidget onPress={onPress} selectedIndex={responseValue} scaleDescriptions={scaleDescriptions} />
          <RadioPagerWidget selectedIndex={pageNumber} />
        </View>
      </Animated.View>
    </LinearGradient>
  );
};

标签: react-nativeuse-effectreact-animated

解决方案


试试这个,但我不确定它是否有效。告诉我它是否适合你。

const [opacity, SetOpacity] = useState(new Animated.Value(0))

...
React.useEffect(() => {
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 1000,
      useNativeDriver: true
    }).start();
  }, [opacity])

...
<RadioInputWidget onPress={() => SetOpacity(opacity.setValue(0))} .../>

推荐阅读