代码之家  ›  专栏  ›  技术社区  ›  khateeb

如何使用react native中的引用更改textinput的值?

  •  0
  • khateeb  · 技术社区  · 7 年前

    我用的是本地的react 0.57.8 并作出反应 16.7.0 . 我正在为Android电视制作一个屏幕键盘,它将被用作图书馆。我有一个 TextInput 我已经给他指派了一个推荐人。如何使用此引用来更改 value 文本输入框 ?

    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";
      }}
    />
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   markmoxx    7 年前

    不能直接在组件中更改属性-只能从父组件派生属性,但不能修改,因此不能执行以下操作:

    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");
      }}
    />
    
        2
  •  0
  •   tbuglc    7 年前

    我认为你需要的是一个可控的输入。 我会这样做:

    constructor(props) {
      super(props);
      this.emailRef = React.createRef(); // might not need this
      this.state = {
        value: ''
      }
    }
    
    <TextInput
      value={this.state.value}
      onChangeText={(text) => this.setState({text})}
      placeHolder="Email Address"
      blurOnSubmit={false}
    />
    
    <Button
      text="change value"
      onPress={() => {
        // just use `this.state.value` to do whatever you need with it
      }}
    />