【问题标题】:Change state from custom button in React Native从 React Native 中的自定义按钮更改状态
【发布时间】:2020-12-15 00:16:11
【问题描述】:

我刚开始使用 React Native,我想通过单击自定义按钮从我的主页更新状态。 我在下面做了这个代码。当我点击我的按钮时,我看不到状态变化。

const Home = () => {
  const welcomeSentence =
    "Bonjour, est ce que tu as fais ton workout aujourd'hui ?";
    const [isWorkoutDone, setIsWorkoutDone] = useState(false);

  return (
    <View style={styles.container}>
      <Text style={styles.homePageText}>{welcomeSentence}</Text>
      <View style={styles.buttonContainer}>
        <AppButton title ="OUI" onPress={()=>this.setIsWorkoutDone(true)}/>
        <AppButton title ="NON" onPress={()=>this.setIsWorkoutDone(false)}/>
      </View>
      <Text>{isWorkoutDone ? "OK" : "KO"}</Text>
    </View>
  );
};

在我的自定义按钮上使用此代码:

const AppButton = (props) => {
  return (
    <Button
      title={props.title}
      onPress={props.onPress}
      style={styles.appButton}
    />
  );
};

我测试并进行了搜索,但我没有找到为什么我的状态没有改变。

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    您正在使用功能组件,因此您不需要this

       <AppButton title ="OUI" onPress={()=>setIsWorkoutDone(true)}/>
       <AppButton title ="NON" onPress={()=>setIsWorkoutDone(false)}/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      • 2016-10-11
      • 1970-01-01
      相关资源
      最近更新 更多