Material-UI Disabled属性不起作用

时间:2018-07-01 21:00:47

标签: javascript reactjs material-ui

单击“完成”后,我试图禁用“编辑”按钮,但它不起作用。我已经在状态中传递了disable属性,但似乎什么也没做,也许不知道是因为setState的异步性质。我在调用setState方法时通过了回调,并且似乎是随机记录数据,有人可以建议该怎么做吗?

class App extends Component {
          state = {
             buttons: {
               id: "test"
             }
           };

          handleCheckBox = id => {
              let buttons = Object.assign({}, this.state.buttons);
              buttons.id = !this.state.buttons[id]
              this.setState({buttons}, ()=>console.log(this.state.buttons));
            }
          render() {
            return (
                <div>
                  {todos.map(todo => (
                  <List key={todo.id}>
                    <ListItem
                      role={undefined}
                      dense
                      button
                    >
                      <Checkbox
                        onClick={()=>this.handleCheckBox(todo.id)}
                        checked={todo.complete}
                        tabIndex={-1}
                        disableRipple
                      />
                      <ListItemText primary={todo.text} />
                      <ListItemSecondaryAction>
                        <Button mini color="secondary" variant="fab" disabled={this.state.buttons[todo.id]}>
                         <Icon>edit_icon</Icon>
                        </Button>
                        ListItemSecondaryAction>
                    </ListItem>
                   </List>
                  ))}
              </div>
            );
          }
        }

1 个答案:

答案 0 :(得分:2)

不是使用id来更改状态,而是使用Array的index来更新状态

在组件state中创建一个数组,该数组跟踪每个按钮的disabled属性

state = {
    buttons: Array(todos.length).fill(false),
      
  };

componentDidMount中,根据待办事项初始化数组

componentDidMount(){
    const buttons=this.state.buttons.slice();
    for(var i=0;i<buttons.length;i++)
        buttons[i]=todos[i].complete;
    this.setState({buttons:buttons})
  }

现在基于要呈现的组件的索引,将按钮状态中的值用于按钮的禁用属性。

<Button mini color="secondary" variant="fab" 
                  disabled={buttons[todos.indexOf(todo)]}>

每当单击CheckBox时,将索引传递到handleChange函数,并更新与索引值相对应的值

<Checkbox 
    onClick={() =>this.handleCheckBox(todos.indexOf(todo))}
    checked={buttons[todos.indexOf(todo)]}{...other}
                />

handleCheckBox = index => {
    const buttons=this.state.buttons.slice();
    buttons[index] = !buttons[index];
    this.setState({
      buttons:buttons
    })
  }

this link中查看SandBox演示