gpt4 book ai didi

javascript - ReactJS:如何访问表单输入子数组?

转载 作者:行者123 更新时间:2023-11-29 18:09:59 27 4
gpt4 key购买 nike

我有以下表格,我希望有一个动态数量的玩家名称输入字段,作为 props.numPlayers 传递给 PlayerSelect,并希望它从每个字段中读取用户输入,并将名称作为数组传递给 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>
);
}
});

最佳答案

您可以使用 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
  • 不要修改组件的 props 以与外部模块通信。使用其他一些提供模型以在组件之间进行通信的库,例如 Backbone 或 Flux(在我的示例中,为简单起见,我只是将收集的玩家名称保存到组件状态)。

关于javascript - ReactJS:如何访问表单输入子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28289000/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com