react-native - React Native TextInput ref 始终未定义

标签 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>

然后我想在我的构造函数中绑定(bind)的函数中使用该 ref:

  constructor(props) {
    super(props);

    this.state = {
      addresses: []
    };

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

添加地址函数:

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

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

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

为什么我好像没有引用资料?

最佳答案

使用状态

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

请记住将您所在州的地址初始化为空字符串,否则地址为空值可能会导致错误。

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(event, result) {
  // I always check to make sure that the ref exists
  if (this._inputElement) {
    console.log("reference:", this._inputElement._lastNativeText);
  }
}

我不推荐第二种方法,因为您正在访问可能会在未来版本中更改的私有(private)方法。

关于react-native - React Native TextInput ref 始终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54560668/

相关文章:

reactjs - 将 Prop 传递给 redux

javascript - 如何使用传感器值检测设备方向?

reactjs - react 引用 : Uncaught TypeError: Cannot set property 'innerHTML' of null

javascript - 如何过滤引用数组

javascript - 定位/滚动到不是紧密父/子的 React 组件

javascript - React Beautiful DND 无法为函数组件提供 refs

ios - 在提供的路径中找不到应用程序包... ":CFBundleIdentifier",不存在

php - 为什么我在后续下载特定文件时在 React Native 中收到 HTTP 412 状态错误?

javascript - react native : Cannot add a child that doesn't have a YogaNode or parent without a measure function

javascript - 转发 ref 到 react.FC 给出类型错误 : Property ref does not exist on type 'IntrinsicAttributes & Props & { children :? ReactNode}