我正在处理一个表单,用户可以动态添加文本字段,并通过按键盘上的下一步移动到新添加的文本字段。
我正在通过以下方式创建动态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>
);
}
}
谁能建议实现这一目标的更好方法。
答案 0 :(得分:0)
您可以使用旧版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
访问它们。