我是React的新手,现在已经坚持了一段时间。我正在创建一个工具,该工具会根据从用户那里收集的姓名列表为乒乓球游戏随机创建配对。我创建了一个输入字段(initialState =''和一个按钮(initialState = []),该函数将名称添加到数组中。我已经在一个单独的Js文件中编写了一些代码,以使数组随机化,并返回在运行时有效的对在终端的节点中。我正在苦苦挣扎的是如何使这些对现在在浏览器中呈现。任何帮助/建议/指针将不胜感激。在此先感谢
import React, { Component, Fragment } from 'react';
class PlayerList extends Component {
constructor(props) {
super(props);
this.state = {
value: '', //empty string for user to input player names
playerNames: [], // empty array to store players name
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.matchPairs = this.matchPairs.bind(this)
}
handleChange(event) {
this.setState({
value: event.target.value
});
}
handleSubmit(event) {
this.setState({
value: '',
playerNames:
this.state.playerNames.concat([this.state.value] + ' '),
});
}
matchPairs(event) {
let playerMatches = this.state.playerNames;
if (playerMatches.length % 2 != 0) {
alert("You must have an even number of players. You currently
have " + playerMatches.length + " players.");
}
/*
Shuffle the provided array.
*/
let shuffle = function(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
/*
Return an array of pairs.
Loop through the array and on each iteration, use ++i to push it
to the next item, so each iteration is actually incrementing i
twice.
*/
let getPairs = function(a) {
let pairs = []; //Create an empty array
for (let i = 0; i < a.length; i++) { // loop through array
pairs.push([ // add a pair to the pairs array
a[i], // get the current array position
a[++i] // increment i to get the next array position
]);
}
return pairs;
}
this.setState({
playerMatches:
this.state.playerMatches.getPairs(shuffle(playerMatches))
});
}
//console.log(getPairs(shuffle(names)));
render() {
return (
<Fragment>
<div className="player-form">
<input className="inputField"
placeholder="Enter Player Name..."
value={this.state.value}
onChange={this.handleChange} />
<p>Player: {this.state.value}</p>
<button className="addBtn"
onClick={this.handleSubmit}>Add Player
</button>
</div>
<button className="generateBtn"
onClick={this.matchPairs}>Generate Pairings
</button>
<div className="player-matches">
<label className="subheadright">Match
Pairings</label>
<ul>
{
this.state.playerMatches.map((item, index) =>
<li key={index}>{item}</li>
)
}
</ul>
</div>
</Fragment>
);
}
}
export default PlayerList;