简体   繁体   English

React Native:钩子 - useRef

[英]React Native: Hooks - useRef

I have been working on ReactJS but totally new to React Native.我一直在研究 ReactJS 但对 React Native 来说是全新的。 I am trying to use useRef on TextInput but it did not work.我正在尝试在 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;

With the code I use in ReactJS above, it always returns me empty string when pressing the button to addName .使用我在上面的 ReactJS 中使用的代码,当按下按钮时它总是返回空字符串addName I also tried to useEffect as below but got the same results.我也useEffect如下使用效果,但得到了相同的结果。

  useEffect(() => {
    if(!inputName.current) return;

    Alert.alert(inputName.current.value);

  }, [inputName.current])

Tried to do some search but I could not find the answer.试图做一些搜索,但我找不到答案。 Can I use useRef in React Native as the same as ReactJS?我可以useRef在 React Native 中使用 useRef 吗?

You can try this:你可以试试这个:

inputName.current._root.props.value

I believe React Native strongly encourages using state instead of ref.我相信 React Native 强烈鼓励使用 state 而不是 ref。 You can get away with useState in this particular case.在这种特殊情况下,您可以摆脱useState

See also Direct Manipulation另见直接操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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