在 React Native 中渲染一个 onPress(TouchableOpacity/Button) 组件

在 React Native 中渲染一个 onPress(TouchableOpacity/Button) 组件

问题描述:

我有一个函数,它有一个对 Wordnik Api 的 fetch 调用,它返回一个随机单词.它一切正常,但我正在尝试设置一个 TouchbaleOpacity/Button,它将在按下该组件时呈现该组件,因此每次用户单击按钮时我都可以获得一个随机词.我在一个单独的文件中有另一个组件,如何在按钮按下时调用它?

I have a functional that has a fetch call to Wordnik Api and it returns one random word. It works all fine, but am trying to set up a TouchbaleOpacity/Button that will render that component onPress so I can get a random word every time the user clicks on the button. I have the other component in a separate file, how do call it on button Press?

`export default function HomeScreen({ navigation }) {
  const onPress = () => {
    //return component
  };
  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <TouchableOpacity onPress={onPress}>
        <Button title="Next word" />
      </TouchableOpacity>
      <Wordnik />
    </View>
  );
}`

在你的组件上添加一个 props key 并且每次在你的按钮的 onPress so 组件上改变那个键每次按键更改时都会呈现如下:

Add a props key on your component and change that key every time on your button's onPress so component will render every time when key change as following :

export default function HomeScreen({ navigation }) {
  const [tempKey, setTempKey] = useState(0);
  const onPress = () => {
    //return component
    setTempKey(tempKey+1);
  };
  return (
    <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
      <TouchableOpacity onPress={onPress}>
        <Button title="Next word" />
      </TouchableOpacity>
      <Wordnik key={tempKey.toString()} />
    </View>
  );
}