【发布时间】:2020-11-16 11:55:39
【问题描述】:
当我们点击开关时,状态“valueState”没有更新我不知道为什么??
另外,我有一个“statusValue”类型问题,因为“switch antd”通过 cons 接受布尔值,道具的初始值是数字类型
这是我正在使用的代码:
// 代码//
import React from 'react';
import { Form, Input, Switch } from "antd";
class UpdateCard extends React.Component {
constructor(props) {
super(props);
this.state = {
valueState: this.props.state.status,
}
}
handleToggle = (checked) => {
console.log("state",this.state.valueState);
console.log("checked",checked);
if (checked === false){
this.setState({
valueState:1
});
}else {
this.setState({
valueState:0
});
}
console.log("handleToggle valueState",this.state.valueState);
};
render() {
const { state } = this.props;
var statusValue = false;
if (state.status === 0) { statusValue = true; }
return (
<Form id='update-state-form'
onFinish={this.onFinish}
onFinishFailed={this.onFinishFailed}
initialValues={{
name: state ? state.name : '',
status: state ? state.status : false,
color: state ? state.color :'',
}}
>
<FormItem {...formItemLayout}
name="name"
label={<IntlMessages id="app.stateName" />}
rules={[{ required: true, message: 'Please input the name !' }]}
>
<Input />
</FormItem>
<FormItem {...formItemLayout}
name="color"
label={<IntlMessages id="app.color" />}
rules={[{ required: true, message: 'Please input the color !' }]}
>
<CirclePicker color={state.color} />
</FormItem>
<FormItem {...formItemLayout}
name="status"
label={<IntlMessages id="app.status" />}
rules={[{ required: true, message: 'Please input the status !' }]}
>
<Switch defaultChecked={statusValue} onClick={this.handleToggle}/>
</FormItem>
</Form>
);
}
}
export default connect(
null,
{
updateStateCardAction,
}
)(UpdateCard );
//****************************** 显示console.log *********** *******************//
【问题讨论】:
-
switch 中的 statusValue 是什么?
-
有两件事,当您调用 this.handleToggle() 时,您没有将任何值作为参数传递,而 setState() 是异步的,因此请记住这一点。 onClick 也只是简单地作为道具传递给 Switch 组件,所以一定要遵循 'antd' 的文档,我个人没有使用过这个库:)
标签: javascript reactjs switch-statement antd setstate