React Native:钩子-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])

试图进行一些搜索,但我找不到答案。我可以在React Native中像使用ReactJS一样使用useRef吗?

lcxs123 回答:React Native:钩子-useRef

您可以尝试以下方法:

inputName.current._root.props.value
,

我相信 React Native 强烈鼓励使用 state 而不是 ref。在这种特殊情况下,您可以使用 useState

另见Direct Manipulation

本文链接:https://www.f2er.com/3169542.html

大家都在问