【问题标题】:Dynamically assigning refs to dynamically created TextInput将 refs 动态分配给动态创建的 TextInput
【发布时间】:2020-08-27 07:59:37
【问题描述】:

我正在开发一个表单,用户可以在其中动态添加文本字段并通过按键盘上的下一步移动到新添加的文本字段。

我正在创建动态 TextField,方法是将文本字段的数量保持在状态,并在用户想要添加文本字段时将它们增加一。

我正在分配与文本字段的 indexes 对应的 ref。 但是当我试图专注于下一个 TextInput onSubmitEditing 我收到一个错误 undefined 不是对象 this[${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>
    );
  }
}

谁能提出一个更好的方法来实现这一点。

【问题讨论】:

  • this。他们有很多方法可以做到这一点

标签: reactjs react-native react-native-android react-native-ios react-ref


【解决方案1】:

您可以使用 Legacy API:String Refs 但不是首选

{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 访问它们。

参考:https://reactjs.org/docs/refs-and-the-dom.html

【讨论】:

    最近更新 更多