简体   繁体   中英

React Native: Hooks - useRef

I have been working on ReactJS but totally new to React Native. I am trying to use useRef on TextInput but it did not work.

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 . I also tried to useEffect as below but got the same results.

  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?

You can try this:

inputName.current._root.props.value

I believe React Native strongly encourages using state instead of ref. You can get away with useState in this particular case.

See also Direct Manipulation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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