[英]Material-UI Disabled attribute not working
單擊完成后,我試圖禁用編輯按鈕,但它不起作用。 我已經在狀態中傳遞了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>
);
}
}
而不是使用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狀態的值用於button的Disabled屬性。
<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 }) }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.