React Material UI复选框:如何通过选中其他框来选中/取消选中组中的其他框?

时间:2019-05-30 07:32:27

标签: javascript reactjs checkbox material-ui state

我设置了3个复选框(“未开始”,“进行中”,“已完成”),我希望在特定时间仅选中一个。

因此,如果自动从“未启动”开始进行检查,如果我选中“已完成”,我将如何取消选中“未启动”?

现在在这里输入我的代码:

在App.js中:

  const newGame = {
     id: uuid.v4(),
     title: title,
     hours: hours,
     notStarted: true,
     inProgress: false,
     completed: false,

  }

  notStarted = (id) => {
    this.setState({games: this.state.games.map(game => {
      if(game.id === id){

        game.notStarted = !game.notStarted
        game.inProgress = false;
        game.completed = false;
      }
    return game;
  })})
};

  markCompleted = (id) => {
this.setState({games: this.state.games.map(game => {
  if(game.id === id){

    game.completed = !game.completed
    game.notStarted = false;
    game.inProgress = false;
  }
  return game;
})})
};

在render()方法中:

<Backlog games={this.state.games} 
        markCompleted={this.markCompleted} 
        inProgress={this.inProgress}
        notStarted={this.notStarted}
/>

这是Game.js中的复选框

<FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.notStarted.bind(this, id)}
          />
      }
      label="Not Started"
/>
<FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.markCompleted.bind(this, id)}
          />
      }
      label="Completed"
/>

截至目前,我可以成功更改道具的状态,但是不确定如何根据状态选择复选框。

2 个答案:

答案 0 :(得分:2)

只需使用radio button而不是复选框。这是默认的无线电行为。

答案 1 :(得分:0)

使用here中的FormControlLabel的属性[已选中]

this.state.games.checked

如果为true,则该组件显示为选中状态。