React-Native:在enter上创建一个新的TextInput行

时间:2019-03-10 13:19:15

标签: javascript reactjs react-native

我想知道如何在按Enter时创建新的TextInput行。因此,就像您要准备一份清单。像这样:

  • [TextInput第一行]

当我按Enter时

  • [TextInput第一行]
  • [TextInput具有焦点的第二行]

另一个输入

  • [TextInput第一行]
  • [TextInput第二行]
  • [TextInput第三行具有焦点等]

感谢所有帮助

1 个答案:

答案 0 :(得分:1)

这是您可以接受的解决方案。我曾使用currying为TextInput事件侦听器创建动态处理程序。您可以在此link上在线查看我的解决方案。

class MyComponent extends Component {
  state = {
    inputValues: [''],
    currentIndex: 0
  }
  inputRefs = []

  handleSubmitEditting = index => () => {
    if (this.state.inputValues[index + 1] === undefined) {
      this.setState({
        currentIndex: this.state.currentIndex + 1,
        inputValues: [...this.state.inputValues, ''] // mutate state (inputValues) & add an empty string
      })
    } else {
      const ref = this.inputRefs[index + 1]
      this.setState({
        currentIndex: index + 1
      }, () => {
        if (ref) {
          ref.focus();
        }
      })
    }
  }

  handleChangeText = index => rawText => {
    const nextInputValues = [...this.state.inputValues] // always mutate state
    nextInputValues[index] = rawText.replace('\n', '')
    this.setState({ inputValues: nextInputValues  })
  }

  handleRef = index => ref => {
    this.inputRefs[index] = ref
    if (index === this.state.currentIndex && ref && !ref.isFocused()) {
      ref.focus();
    }
  }

  render() {
    const { inputValues } = this.state;
    return (
      <View>
        {inputValues.map((value, index) => (
          <TextInput
            key={index}
            ref={this.handleRef(index)}
            value={value}
            onSubmitEditting={this.handleSubmitEditting(index)}
            onChangeText={this.handleChangeText(index)}
          />
        ))}
      </View>
    )
  }
}