react-native - React Native TextInput 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(event, result) {
console.log("reference:", this._inputElement.value);
}
render 和 addAddress 中的控制台日志始终未定义。
我环顾四周,但似乎没有人遇到我的问题,通常他们有错字或没有绑定他们想要调用的函数。
为什么我似乎无法获得参考?
解决方案
使用状态
通常使用的方式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
addAddress(event, result) {
// I always check to make sure that the ref exists
if (this._inputElement) {
console.log("reference:", this._inputElement._lastNativeText);
}
}
我不推荐第二种方法,因为您正在访问可能在未来版本中更改的私有方法。
推荐阅读
- python - 如何计算新列中的累积加权平均值?
- vb.net - 我如何将一个巨大的字符串分成更小的部分?
- java - 如何使用 indexOf() 函数查找具有特定属性的对象
- javascript - 将循环更改为 Promise.all()
- javascript - Javascript 排序在中间停止工作
- android - Android 上的 KeyboardAvoidingView 在键盘上方创建一个灰色框
- ansible - 使用 pm2 管理多个应用程序/ecosystem.config.js 文件
- reactjs - 如何将标签包装在
与 ConnectedRouter? - reactjs - 在 React 中从另一个表单中提交表单
- reactjs - React + Mobx 如何改变不同组件的值并在各处显示变化?