React Native TextInput ref始终未定义

时间:2019-02-06 18:53:18

标签: react-native react-ref

我有一个简单的TextInput,我想在我的渲染器中添加一个引用:

      <View>
        <TextInput ref={(component) => this._inputElement = component}>Input</TextInput>
        {console.log(this._inputElement)}
        <Button
          onPress={this.addAddress}
          title="Submit"
          color="#841584"
        />
      </View>

然后我想在构造函数中绑定的上述函数中使用该引用:

  constructor(props) {
    super(props);

    this.state = {
      addresses: []
    };

    this.addAddress = this.addAddress.bind(this);
  }

addAddress函数:

  addAddress(event, result) {
    console.log("reference:", this._inputElement.value);
  }

render和addAddress中的控制台日志始终未定义。

我环顾四周,但似乎没有人遇到我的问题,通常他们输入错误或没有绑定他们想要调用的函数。

为什么我似乎无法获得参考?

2 个答案:

答案 0 :(得分:2)

使用状态

通常,使用TextInput的方法是将值存储在状态中。

请记住,将您状态下的地址初始化为空字符串,否则为null设置地址可能会导致错误。

constructor(props) {
  super(props)
  this.state = {
   ....
   address: ''
  }
}

然后您可以按以下方式定义文本输入

<TextInput
  onChangeText={address => this.setState({address})}
  value={this.state.address}
/>

然后在您的addAddress中

addAddress(event, result) {
  console.log("reference:", this.state.address);
}

使用参考

或者,您可以使用._lastNativeText从引用中访问

<TextInput 
  ref={ref => { this._inputElement = ref }}>
  Input
</TextInput>

然后在您的addAddress中

addAddress(event, result) {
  // I always check to make sure that the ref exists
  if (this._inputElement) {
    console.log("reference:", this._inputElement._lastNativeText);
  }
}

当您访问的私有方法可能会在将来的版本中更改时,我不建议使用第二种方法。

答案 1 :(得分:1)

文本输入自包含

<View>
        <TextInput ref={ref=> (this._inputElement = ref)}/>
        <Button
          onPress={this.addAddress}
          title="Submit"
          color="#841584"
        />
      </View>


addAddress(event, result) {
    console.log("reference:", this._inputElement._lastNativeText); //this get's the value, otherwise it's undefined
  }
相关问题