在下面的代码中,我得到一个编译错误,我无法在closeLeftCol中更改状态:
Cannot assign to leftWidth because it is a constant or read only property
:
interface ILayoutState{
rightClassName: string,
leftClassName: string,
leftWidth: string,
rightWidth : string
}
export default class Layout extends React.Component<undefined, ILayoutState> {
constructor(props) {
super(props);
this.state = {
rightClassName: "right-col slide-in", leftClassName: "left-col slide-in", leftWidth: '' ,rightWidth : '' };
}
closeLeftCol() {
this.state.leftWidth = "0";
this.state.rightWidth = "100%";
this.state.leftClassName += " hideme";
this.state.rightClassName += " full";
this.forceUpdate();
}
render() {...}
}
答案 0 :(得分:1)
Never mutate this.state directly ,始终使用setState来更新state
值。
像这样写:
closeLeftCol() {
this.setState(prevState => ({
leftWidth : "0",
rightWidth : "100%",
leftClassName : prevState.leftClassName + " hideme",
rightClassName : prevState.rightClassName + " full"
}));
}
答案 1 :(得分:0)
其他地方constructor
,您需要调用setState
方法来更改state
。
closeLeftCol() {
this.setState({
//change state here
leftWidth: "0",
rightWidth: "100%",
leftClassName: this.state.leftClassName + " hideme",
rightClassName: this.state.rightClassName + " full"
})
//or use this way
this.setState((prevState)=>{
return {
//change state here
leftWidth: "0",
rightWidth: "100%",
leftClassName: prevState.leftClassName + " hideme",
rightClassName: prevState.rightClassName + " full"
}
})
}