我有一个播放器表单,需要多个播放器输入,提交后,所有播放器都会添加到mongodb集合中。我不确定最好的方法是处理多个输入。到目前为止,下面的代码仅提供一个玩家的输入。如果我想添加多个输入以最多增加10个玩家,那么每个输入字段都需要有一个唯一的名称吗?如果是这样,它将如何适合我的addPlayerToTeam函数?预先感谢!
export default class AddPlayersForm extends Component {
constructor(props) {
super(props);
this.submitForm = this.submitForm.bind(this);
}
submitForm(event) {
event.preventDefault();
this.props.addPlayerToTeam({
firstName: event.target.firstName.value,
lastName: event.target.lastName.value,
email: event.target.email.value,
height: event.target.height.value,
})
}
render() {
return (
<div>
<h2>Add players</h2>
<h4>Must have a minimum of 5 players to complete registration</h4>
<Table>
<Form onSubmit={(event) => this.submitForm(event)}>
<FormGroup>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Height</th>
</tr>
<InputGroup>
<tr>
<td><Input type="text" name="firstName" id="firstName" /></td>
<td><Input type="text" name="lastName" id="lastName" /></td>
<td><Input type="text" name="email" id="email" /></td>
<td><Input type="text" name="height" id="height" /></td>
</tr>
</InputGroup>
</thead>
</FormGroup>
</Form>
</Table>
</div>
)
}
}
嗨,我为您准备了一个例子。您可以根据需要使用它。仅供参考,我评论了这一行this.props.addPlayersToTeam(this.state.players);但是您可以取消注释它,并在父组件中实现addPlayersToTeam以在我们在参数中传递玩家时将多个玩家保存在一起。
import React from 'react';
import {Input} from "reactstrap";
export default class AddPlayersForm extends React.Component {
constructor(props) {
super(props);
this.state = {
players: [],
currentPlayer: {
firstName: '',
lastName: '',
email: '',
height: ''
}
};
}
save = (event) => {
event.preventDefault();
console.log(JSON.stringify(this.state.players), 'players');
// this.props.addPlayersToTeam(this.state.players);
};
onChange = (event) => {
event.preventDefault();
this.setState({currentPlayer: {...this.state.currentPlayer, [event.target.name]: event.target.value}});
};
addPlayer = (event) => {
event.preventDefault();
this.setState(state => {
let found = state.players.find(p => p.firstName === state.currentPlayer.firstName && p.lastName === state.currentPlayer.lastName);
if(!found) {
return state.players.push(state.currentPlayer);
}
}, () => {
console.log(this.state.players, 'players');
});
};
render() {
return (
<div>
<h2>Add players</h2>
<h4>Must have a minimum of 5 players to complete registration</h4>
<form>
<table>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Height</th>
</tr>
<tr>
<td><Input onChange={this.onChange} type="text" name="firstName" id="firstName"/></td>
<td><Input onChange={this.onChange} type="text" name="lastName" id="lastName"/></td>
<td><Input onChange={this.onChange} type="text" name="email" id="email"/></td>
<td><Input onChange={this.onChange} type="text" name="height" id="height"/></td>
</tr>
</thead>
</table>
<button onClick={this.addPlayer}>Add Player</button>
<button onClick={this.save}>Save</button>
</form>
</div>
)
}
}