React Native Expo中onPress事件触发时创建新组件的解决方案咨询
核心问题说明
你当前的写法无法生效,是因为onPress回调的返回值不会被自动插入到组件树中渲染,React Native的UI更新完全依赖状态驱动,你需要通过状态变量控制动态组件的显隐或生成,同时注意你原代码里的TouchableOpacity存在拼写错误,实际使用时需要修正。
基础实现(点击显示单个新组件)
通过useState定义布尔状态控制第二个组件的显隐即可:
import { useState } from 'react'; import { View, TouchableOpacity, Text, StyleSheet } from 'react-native'; export default function App() { // 控制第二个按钮是否显示的状态 const [showSecondBtn, setShowSecondBtn] = useState(false); return ( <View> <TouchableOpacity style={styles.container} onPress={() => setShowSecondBtn(true)} > <Text>点击显示新按钮</Text> </TouchableOpacity> {/* 条件渲染:状态为true时才渲染第二个组件 */} {showSecondBtn && ( <TouchableOpacity> <Text>Hello World</Text> </TouchableOpacity> )} </View> ) } const styles = StyleSheet.create({ container: { padding: 16, backgroundColor: '#e0e0e0', margin: 10 } })
扩展实现(点击生成多个新组件)
如果需要每次点击都新增一个独立组件,可以把状态定义为数组,每次点击往数组中追加元素,渲染时遍历数组生成对应组件:
import { useState } from 'react'; import { View, TouchableOpacity, Text, StyleSheet } from 'react-native'; export default function App() { // 数组存储所有动态生成的组件数据 const [btnList, setBtnList] = useState([]); const addNewBtn = () => { setBtnList([...btnList, { id: Date.now(), text: `按钮${btnList.length + 1}` }]) } return ( <View> <TouchableOpacity style={styles.container} onPress={addNewBtn} > <Text>点击新增按钮</Text> </TouchableOpacity> {/* 遍历数组生成所有动态组件 */} {btnList.map(item => ( <TouchableOpacity key={item.id} style={styles.newBtn}> <Text>{item.text}</Text> </TouchableOpacity> ))} </View> ) } const styles = StyleSheet.create({ container: { padding: 16, backgroundColor: '#e0e0e0', margin: 10 }, newBtn: { padding: 12, backgroundColor: '#f5f5f5', marginHorizontal: 10, marginVertical: 5 } })
内容的提问来源于stack exchange,提问作者WHXY
相关产品推荐
相关产品推荐

