我正在创建一个足球博彩应用程序,我想在其中选择一场比赛的赢家/输家/平局,然后将其存储在选定的赌注列表中。
对于每场比赛,您都可以选择团队或平局的获胜者。 # !! Clears the screen, but prints the cmd.exe prompt string once.
bash$ echo cls | cmd
方法作为道具向下传递给每个按钮的getSelection
处理程序。
然后,onClick
方法将按钮click的值添加到数组中,如下所示:
getSelection
我只希望对每个匹配项进行一次选择,就象这样直观地表示:
答案 0 :(得分:1)
此解决方案正在根据用户的选择更新匹配结果。
单个匹配将具有单个结果,即结果将被覆盖
我也使用matchNumber
作为索引来跟踪比赛编号。
您的getSelection
看起来像这样。
getSelection = (val: object, matchNumber: number) => {
// 1. Make a shallow copy of the items
let bets = [...this.state.bets];
// 2. Make a shallow copy of the item you want to mutate
let bet = { ...bets[matchNumber] };
// 3. Replace the property you're intested in
bet = val;
// 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
bets[matchNumber] = bet;
// 5. Set the state to our new copy
this.setState({ bets }, () => console.log(this.state.bets));
更新背景:
<button
style={{ background: winner == home.name ? "lightblue" : "white" }}
onClick={() => this.props.getSelection(home, matchNumber)}
>
{home.name}
</button>
<button
style={{ background: winner == draw.name ? "lightblue" : "white" }}
onClick={() => this.props.getSelection(draw, matchNumber)}
>
{draw.name}
</button>
<button
style={{ background: winner == away.name ? "lightblue" : "white" }}
onClick={() => this.props.getSelection(away, matchNumber)}
>
{away.name}
</button>
检查此工作解决方案。 https://codesandbox.io/s/9lpnvx188y
答案 1 :(得分:0)
您是说一次只能添加一次可能性吗? 然后这可能会起作用:
getSelection = (val: object) => {
this.setState( {
bets: [...this.state.bets, val].filter((value, index, self) => { return self.indexOf(value) === index; })
},
() => console.log(this.state.bets, "bets")
);
};
(也就是说,获取整个数组,添加新值,进行过滤,以便仅获取不同的值,并将其存储在赌注中。)