繁体   English   中英

React Native:钩子 - useRef

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM