如何在不定义value属性、不使用useState的情况下获取TextInput的文本?
完全可以实现不使用useState受控模式的表单需求,不会触发多余的组件重渲染。你之前获取ref的value为undefined,是因为这个属性是受控模式下传入的props,而非输入框原生存储的实际输入值,你可以通过以下两种方案实现需求:
方案1:将输入值存入useRef(最稳妥,推荐使用)
只需要在onChangeText回调中把输入值写入ref即可,ref的更新不会触发组件重渲染,完全满足你不需要每次输入刷新屏幕的要求,取值时直接访问ref的current属性即可。
完整示例代码如下:
import { useRef } from 'react'; import { View, TextInput, Button, Alert, StyleSheet } from 'react-native'; const Home = () => { // 存储输入值的ref,更新不会触发重渲染 const inputValueRef = useRef(''); const inputRef = useRef<TextInput>(null); const handleSubmit = () => { // 点击按钮时直接取ref里存的输入值 const inputText = inputValueRef.current; Alert.alert('当前输入内容', inputText); }; return ( <View style={styles.container}> <TextInput style={styles.input} ref={inputRef} onChangeText={(text) => inputValueRef.current = text} /> <Button title="获取输入值" onPress={handleSubmit} /> </View> ); }; const styles = StyleSheet.create({ container: { padding: 20, marginTop: 50 }, input: { height: 40, borderColor: '#ccc', borderWidth: 1, marginBottom: 20, paddingHorizontal: 10 } }); export default Home;
方案2:直接读取输入框原生属性(无需写onChangeText,兼容性稍弱)
如果连onChangeText都不想写,也可以直接通过TextInput的ref访问原生属性获取当前输入值,不过该方式依赖React Native的内部实现,不同版本可能存在属性名差异:
const handleSubmit = () => { // 读取原生属性获取输入值 const inputText = inputRef.current?.getNativeProps().text ?? ''; Alert.alert('当前输入内容', inputText); };
内容的提问来源于stack exchange,提问作者Jancer Lima
相关产品推荐
相关产品推荐

