javascript - 如何在 React Native 中使用引用更改 TextInput 的值?

标签 javascript reactjs react-native

我正在使用 React Native 0.57.8 和 React 16.7.0。我正在为 Android TV 创建一个屏幕键盘,它将用作一个库。我有一个 TextInput,我已为其分配了一个引用。我如何使用此引用来更改 TextInputvalue

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";
  }}
/>

最佳答案

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

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

关于javascript - 如何在 React Native 中使用引用更改 TextInput 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54214114/

相关文章:

git - 以 'expo init my-project'启动的React Native项目无法推送到github?

reactjs - 重新绘制 Y 轴间隔问题

react-native - React Native (0.59.10) — 如何在运行测试时删除 `useNativeDriver`(但不是在实际应用程序中)

javascript - 永久保存jquery修改的页面

javascript - 设置值后 Chrome 11+(可能还有 IE)不会触发 OnChange

html - 我们如何使放置在链接标记内的 div 成为不可导航的

javascript - React js Router 更改 url 但不加载页面

android - 构建失败,在 React Native android 中出现异常

javascript - 处理来自 SoundCloud Widget 的 JS 事件

javascript - 更新 HTML 以使用 JavaScript 或 jQuery 结束标记