我一直在研究ReactJS,但对React Native来说是全新的。我正在尝试在TextInput上使用useRef
,但是没有用。
const Playground = () =>{
const inputName = useRef();
const addName = e => {
Alert.alert(inputName.current.value);
}
return (
<SafeAreaView>
<TextInput ref={inputName} placeholder="name"></TextInput>
<Button title="add" onPress={addName}></Button>
</SafeAreaView>
);
}
export default Playground;
使用上面我在ReactJS中使用的代码,当按下addName
按钮时,它总是返回空字符串。我也尝试如下进行useEffect
,但结果相同。
useEffect(() => {
if(!inputName.current) return;
Alert.alert(inputName.current.value);
}, [inputName.current])
试图进行一些搜索,但我找不到答案。我可以在React Native中像使用ReactJS一样使用useRef
吗?
答案 0 :(得分:0)
您可以尝试以下方法:
inputName.current._root.props.value
答案 1 :(得分:0)
我相信 React Native 强烈鼓励使用 state 而不是 ref。在这种特殊情况下,您可以使用 useState
。