首页 > 解决方案 > 如何使用 React Native 中的引用更改 TextInput 的值?

问题描述

我正在使用 React Native0.57.8和 React 16.7.0。我正在为 Android TV 创建一个屏幕键盘,将用作库。我有一个TextInput我分配给他的参考。如何使用此参考来value更改TextInput?

constructor(props) {
  super(props);
  this.emailRef = React.createRef();
}

<TextInput
  ref={this.emailRef}
  placeHolder="Email Address"
  blurOnSubmit={false}
/>

<Keyboard textInput={this.emailRef} />

图书馆内:

<Button
  text="change value"
  onPress={() => {
    this.props.emailRef.current.props.value =
      this.props.emailRef.current.props.value + "q";
  }}
/>

标签: javascriptreactjsreact-native

解决方案


他们都说使用状态,但不知道为什么我确实需要在不使用状态的情况下更新 UI。在我的例子中,文本输入正在使用状态,当输入非常快时,异步状态和 UI 更新滞后于输入速度,并且光标滞后几个字母,导致输入错误。防止这种情况的唯一方法是不使用任何状态!如果你不使用状态,你不能给文本输入一个初始值而不使它成为只读的。为了给 TextInput 一个初始值,我们可以使用 ref 并在组件挂载事件时以编程方式设置原生 props。像这样:

const setInitialBio = React.useCallback(() => {
    if(inputRef.current) {
        inputRef.current.setNativeProps({ text: "initial value goes here" })
    }
}, []);

推荐阅读