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

编程入门 行业动态 更新时间:2024-10-28 15:28:39
本文介绍了在 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) 组件

本文发布于:2023-11-27 23:45:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640091.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   Native   React   onPress   Button

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!