【问题标题】:How to use function with Animated.timing and setState?如何使用 Animated.timing 和 setState 的函数?
【发布时间】:2020-05-15 22:13:24
【问题描述】:

我在将 Animated.timing 与 setState 结合使用时遇到问题。

export default function Main() {

  const [stateMenu, setStateMenu] = useState(false);
  const translateY = new Animated.Value(0);

  const {width, height} = Dimensions.get('window');

function Descer() {
    Animated.timing(translateY, {
        toValue: 800,
        duration: 2000,
        useNativeDriver: false
    }).start();
}

//(1) - With the "Teste" function, this works perfectly.
function teste()
{
  Descer();
  //setStateMenu(!stateMenu);
}

//(2) - In this way nothing happens.
function teste()
{
  Descer();
  setStateMenu(!stateMenu);
}


  return (
    <Container>
      <Header onPress={() => teste()} state={stateMenu}/>
      <Scene>
        <Menu/>
        <ScenePage style={[{flex:1, position:'absolute', top:0, left:0, zIndex:15, width:'100%', height:height }, {top:translateY}]}>
          <Routes />
        </ScenePage>

      </Scene>

    </Container>
  )
};

我没有两个“Teste”函数,我放了两个只是为了解释会发生什么。

我需要使用第二种方式,为什么它不起作用?

【问题讨论】:

    标签: react-native react-hooks react-animated


    【解决方案1】:

    要将setStateMenu 与先前的状态值一起使用,您需要将具有先前状态的函数作为参数传递。尝试像这样更改 setStateMenu 调用:

    setStateMenu(prevState => !prevState);
    

    【讨论】:

    • 抱歉没看懂。什么是“prevState”?
    • @Joelend 当您使用setStateMenu 时,您无法直接访问stateMenu 值,因此解决方案是传递一个函数。这个函数接受之前的stateMenu 值作为参数,你可以随意命名这个参数(在这个例子中我将它命名为prevState)。 See more in docs
    • 我明白了,我在这里做了......就像以前一样。即使有您的建议,Animated.timing 仍然无法运行。
    猜你喜欢
    • 2018-01-20
    • 2020-04-13
    • 2020-02-10
    • 2018-10-05
    • 2021-12-04
    • 2020-10-08
    相关资源
    最近更新 更多