gpt4 book ai didi

javascript - 在渲染之前更改从 Prop 派生的状态

转载 作者:行者123 更新时间:2023-11-30 19:48:31 25 4
gpt4 key购买 nike

我有以下 React MUI切换组件,它在 Prop checked = {this.state.checked}

上更改其 ui 状态

class Switch extends Component {
state = {
active : this.props.contData.statesValue.active,
checked: false
}
render() {
const { classes, theme } = this.props;
return (
<MuiSwitch checked={this.state.checked}/>
)
}
}

switch 期望被检查的 prop 是一个字符串,'true' | “假”

我正在尝试使用状态 active 设置选中的 Prop :this.props.contData.statesValue.active,但是,这是作为 bool 0 1 接收的,当传递到 Switch Prop 时作为 checked={this.state.active} 导致错误

Failed prop type: Invalid prop checked supplied to SwitchBase.

所以我的问题是如何将传入的事件 Prop 从 0 1 更改为字符串 'true' | 'false' 在呈现组件之前。以前我会看一下 componentWillReceiveProps 方法,但由于现在已弃用,欢迎任何有关如何实现此方法的指示。

最佳答案

MUI's Switch可以为 checked 属性使用字符串或 bool 值,v1.0+。

在这种情况下,我们在初始化状态时将 prop 转换为 bool 值,使用久经考验的 !! 双重否定:

class Switch extends Component {
state = { active: !!this.props.contData.statesValue.active };

render() {
return <MuiSwitch checked={this.state.active}/>;
}
}

关于javascript - 在渲染之前更改从 Prop 派生的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54718281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com