在Expo React Native中,如何点击父容器唤起TextInput编辑状态?
解决方案
当然可行,你只需要给TextInput添加一个ref,然后在TouchableOpacity的onPress事件里调用输入框的focus()方法,就能让它进入编辑状态。
具体修改代码如下:
import { useRef } from 'react'; import { TouchableOpacity, View, Text, TextInput } from 'react-native'; // 你的组件内部逻辑 const inputRef = useRef(null); return ( <TouchableOpacity onPress={() => inputRef.current?.focus()}> <View style={styles.container}> <Text> Protein</Text> <TextInput ref={inputRef} // 绑定引用到输入框 style={styles.input} onChangeText={(event) => setItem(prevState => ({ ...prevState, proteins: parseInt(event) }))} keyboardType={'numeric'} value={item.proteins?.toString()} // 注意:数字类型值要转成字符串,避免TextInput警告 placeholder='0' /> </View> </TouchableOpacity> );
- 用
useRef创建引用对象inputRef,关联到目标TextInput上 - 在TouchableOpacity的点击事件中,调用
inputRef.current?.focus()触发输入框聚焦,可选链?.是为了避免组件未挂载时的报错 - 额外提示:TextInput的
value必须是字符串类型,如果item.proteins是数字,记得转成字符串格式
内容的提问来源于stack exchange,提问作者benwl
相关产品推荐
相关产品推荐

