【问题标题】:React Material UI Checkbox: How to check/uncheck other boxes in group by checking a different box?React Material UI Checkbox:如何通过选中不同的框来选中/取消选中组中的其他框?
【发布时间】:2019-10-15 20:11:38
【问题描述】:

我设置了 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"
/>

到目前为止,我可以成功更改道具的状态,但是我不确定如何根据状态使框选中/取消选中?

【问题讨论】:

    标签: javascript reactjs checkbox material-ui state


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      使用来自 here 的 FormControlLabel 的 Prop [选中]

      this.state.games.checked
      

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

      【讨论】:

        猜你喜欢
        • 2013-06-24
        • 2014-06-25
        • 2019-06-04
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多