React-Native:访问TextInput中的关键道具

时间:2018-01-20 21:36:15

标签: react-native key textinput

我尝试访问TextInput中的key prop以将其保存在状态中(然后在Redux中)。我在数组中创建了许多TextInput字段,就像我从第一个屏幕中获得的那样:

render() {
    const { playerAmount } = this.props;
    var textBoxes = [];
    for (var i = 0; i < playerAmount; i++) {
      var placeholderText = 'Player ' + (i + 1);
      textBoxes.push(
        <TextInput
          key = {i+1}
          onChangeText={(text) => {
            const Player = Object.assign({}, this.state.Player, { playerName: text, playerNumber: this.props.key});
            this.setState({ Player });
          }}
          placeholder={placeholderText}
          placeholderTextColor="grey"
        >
        </TextInput>

      );

现在我尝试用关键道具设置playerNumber的状态。我用key / {key} / this.props.key

尝试了

构造

  constructor(props) {
    super(props);
    this.state = 
    {
      Player: 
      {
        playerName: "",
        playerNumber: 0
      }
    }

  }

正如你所看到的,我对React-Native很新。你知道如何解决这个问题吗?

非常感谢你! :)

2 个答案:

答案 0 :(得分:1)

为什么不这样做?

render() {
  const { playerAmount } = this.props;
  var textBoxes = [];
  for (var i = 0; i < playerAmount; i++) {
    var placeholderText = 'Player ' + (i + 1);
    const key = i+1;
    textBoxes.push(
          <TextInput
              key = {key}
              onChangeText={(text) => {
                const Player = Object.assign({}, this.state.Player, { playerName: text, playerNumber: key});
                this.setState({ Player });
              }}
              placeholder={placeholderText}
              placeholderTextColor="grey"
          >
          </TextInput>
    );
  }
}

答案 1 :(得分:0)

class Firebase extends React.Component{
  state={
    name:'',
    number:'',

  }
  onChangeTextInput = key => val => {
    this.setState({[key]:val})
  }
  render(){
    return(
      <View>
        <TextInput
        value={this.state.name}
        onChangeText={this.onChangeTextInput('name')}
        />
         <TextInput
        value={this.state.number}
        onChangeText={this.onChangeTextInput('number')}
        />
      </View>
    )
  }
}