我一直在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])我试着做了一些搜索,但我找不到答案。我可以像使用ReactJS一样在React Native中使用useRef吗?
发布于 2019-11-19 13:29:59
您可以尝试这样做:
inputName.current._root.props.value发布于 2021-03-04 06:25:48
我相信React Native强烈建议使用state而不是ref。在这种特殊情况下,您可以使用useState。
https://stackoverflow.com/questions/58686093
复制相似问题