我有以下表单,我希望有一个动态数量的玩家名称输入字段,作为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>
);
}
});
答案 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>
);
}
});
还要记住:
key