在 React Native 中渲染一个 onPress(TouchableOpacity/Button) 组件 [英] Render a component onPress(TouchableOpacity/Button) in React Native

查看:93
本文介绍了在 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>
  );
}

这篇关于在 React Native 中渲染一个 onPress(TouchableOpacity/Button) 组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆