ReactJS:如何访问表单输入子元素数组?

时间:2015-02-02 23:50:51

标签: javascript arrays forms input reactjs

我有以下表单,我希望有一个动态数量的玩家名称输入字段,作为PlayerSelect传递给props.numPlayers,并希望它从每个输入中读取用户输入字段并将名称作为数组传递给this.props.setPlayers,这是从父组件传递的回调。

我正在尝试找到从父级访问PlayerNameInput组件的正确方法,因为以下似乎无法正常工作:

var PlayerSelect = React.createClass({
  getPlayers: function() {
    var playerNames = []
    for (var i = 0; i < this.players.length; i++) {
      var playerName = this.players[i].getDOMNode().value.trim();
      playerNames.push(playerName);
    }
    this.props.setPlayers(playerNames);
  },
  render: function() {
    this.players = []
    for (var i = 0; i < this.props.numPlayers; i++) {
      this.players.push(<PlayerNameInput />);
    }
    return (
      <div className="page">
        <form className="player-select">
          <ol className="players">
            {this.players}
          </ol>
          <button onClick={this.getPlayers}>Done</button>
        </form>
      </div>
    );
  }
});

var PlayerNameInput = React.createClass({
  render: function() {
    return (
      <li><input type="text"/></li>
    );
  }
});

1 个答案:

答案 0 :(得分:4)

您可以使用ref访问DOM节点:

var PlayerSelect = React.createClass({
  getInitialState: function() { return { names: [] } },
  getPlayers: function(event) {
    event.preventDefault();
    var playerNames = []
    for (var i = 0; i < this.props.numPlayers; i++) {
      var playerName = this.refs['player-' + i].getDOMNode().value.trim();
      playerNames.push(playerName);
    }
    this.setState({ names: playerNames });
  },
  render: function() {
    var players = []
    for (var i = 0; i < this.props.numPlayers; i++) {
      players.push(
          <li key={'player-' + i}>
              <input ref={ 'player-' + i } type="text"/>
          </li>
      );
    }
    return (
      <div className="page">
        <form className="player-select">
          <ol className="players">
            {players}
          </ol>
          <button onClick={this.getPlayers}>Done</button>
        </form>
        <div>{ this.state.names.join(', ') }</div>
      </div>
    );
  }
});

JSFiddle

还要记住:

  • 创建元素数组时,每个元素都必须具有唯一的key
  • 不要修改组件的道具以与外部模块通信。使用一些其他库来提供组件之间的通信模型,例如Backbone或Flux(在我的例子中,为了简单起见,我只是将收集的玩家名称保存到组件状态)。