如何解决将引用动态分配给动态创建的TextInput
我正在处理一个表单,用户可以动态添加文本字段,并通过按键盘上的下一步移动到新添加的文本字段。
我正在通过以下方式创建动态TextField:将文本字段的编号保持在该状态,并在用户想要添加Text字段时将它们增加一。
我要分配与文本字段的索引相对应的引用。
但是,当我尝试着重于下一个TextInput onSubmitEditing时,出现错误
未定义不是此对象[${idx + 1}_ref
。focus()
class FieldCollection extends React.PureComponent {
constructor(props) {
super(props);
const {values} = props;
this.state = {
noOfFields: values || [1],};
}
addField = () =>
this.setState(({noOfFields}) => {
const _ = [...noOfFields];
_.push(1);
return {
noOfFields: _,};
});
render() {
const {noOfFields} = this.state;
return (
<View style={styles.section}>
{noOfFields.map((_,idx) => (
<View style={styles.fieldsConatainer}>
<TextInput
placeholder={'Email'}
returnKeyType={'next'}
.
.
.
ref={input => {
this[`${idx}_ref`] = input;
}}
onSubmitEditing={event => {
this[`${idx + 1}_ref].focus(); // focusing on the next input
}} // throws undefined error
/>
</View>
<TouchableOpacity onPress={this.addField}>
.
.
</TouchableOpacity>
))}
</View>
);
}
}
谁能建议实现这一目标的更好方法。
解决方法
您可以使用旧版API:字符串引用,但不是首选
{noOfFields.map((_,idx) => (
<View style={styles.fieldsConatainer}>
<TextInput
placeholder={'Email'}
returnKeyType={'next'}
.
.
.
ref={`${idx}_ref`}
onSubmitEditing={event => {
this[`${idx + 1}_ref].focus(); // focusing on the next input
}} // throws undefined error
/>
</View>
<TouchableOpacity onPress={this.addField}>
.
.
</TouchableOpacity>
))}
您可以通过this.refs
访问它们。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。