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

新手上路,请多包涵

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

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

原文由 khateeb 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 535
2 个回答

您不能直接在组件内更改道具 - 道具只能从父组件派生,但不能修改,因此您不能:

this.props.emailRef.current.props.value = this.props.emailRef.current.props.value + "q";

此外,您在库中引用了 this.props.emailRef ,而键盘没有 emailRef 道具 - 它具有 textInput 道具。

尝试这个:

 constructor(props) {
  super(props);
  this.emailRef = React.createRef();
  this.state = {
    value: "Initial Input"
  };
  this.handleInput = this.handleInput.bind(this);
}

handleInput(input) {
  this.setState({ value: input });
}

render() {
  return (
    ...
      <Keyboard textInput={this.emailRef} onInput={this.handleInput} />
      <TextInput ref={this.emailRef} value={this.state.value} />
    ...
  );
}

图书馆内部:

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

原文由 markmoxx 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

原文由 nodir.dev 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题