[英]React Native: Hooks - useRef
我一直在研究 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])
試圖做一些搜索,但我找不到答案。 我可以useRef
在 React Native 中使用 useRef 嗎?
你可以試試這個:
inputName.current._root.props.value
我相信 React Native 強烈鼓勵使用 state 而不是 ref。 在這種特殊情況下,您可以擺脫useState
。
另見直接操作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.