React Native中ref.current.value在真机/模拟器无法获取TextInput值
问题原因
ref.current.value是Web端DOM输入元素的标准属性,React Native iOS/Android端的原生TextInput组件实例并未对外暴露该属性,仅react-native-web在Web编译层做了API对齐,因此会出现Web端取值正常、真机/模拟器返回空的现象。
推荐实现方案
RN官方优先推荐使用受控组件模式处理输入框取值:通过onChangeText回调实时同步输入内容到组件state,需要取值时直接读取对应state即可,该方案全端兼容,稳定性最高。
修正后可运行的代码:
import * as React from 'react'; import { Text, View, StyleSheet, TextInput, Button } from 'react-native'; import Constants from 'expo-constants'; export default function App() { const [val, setVal] = React.useState('NA'); // 单独维护输入框内容状态 const [inputText, setInputText] = React.useState(''); const handleClick = () =>{ setVal(inputText) } return ( <View style={styles.container}> <TextInput placeholder="name..." style={{backgroundColor: 'white', padding: 5, paddingLeft: 10, paddingBottom: 10}} value={inputText} onChangeText={setInputText} /> <Button title="Click" onPress={handleClick} /> <Text style={{height: 100, color: 'red', backgroundColor: 'lightblue', padding: 5}}> {val} </Text> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', padding: 8, } });
其他方案(不推荐)
如果特殊场景必须通过ref取值,原生端可通过inputRef.current._lastNativeText获取当前输入内容,但该属性属于组件内部未公开属性,随RN版本迭代存在变动风险,非必要不使用。
内容的提问来源于stack exchange,提问作者rens
相关产品推荐
相关产品推荐

