validateFields()
接受两个参数。您应该提供{force: true}
作为正确验证该字段的第二个参数。
handleChangeAttributeActive = e => {
this.setState(
prevState => ({
...prevState,
attribute: { ...prevState.attribute, isActive: e.target.checked }
}),
() => {
this.props.form.validateFields([e.target.value], { force: true });
}
);
};
validateFields https://ant.design/components/form/?locale=en-US验证指定字段并获取它们的值
和错误。如果不指定fieldNames参数,则会
验证所有字段。
import { Row, Col, Checkbox, Form, Input } from "antd";
class App extends Component {
state = {
attribute: {
name: "name",
isActive: true,
eventId: 1,
attributeSendName: "enter your name"
},
isViewMode: false
};
handleChangeAttributeActive = e => {
this.setState(
prevState => ({
...prevState,
attribute: { ...prevState.attribute, isActive: e.target.checked }
}),
() => {
this.props.form.validateFields([e.target.value], { force: true });
}
);
};
render() {
const { getFieldDecorator } = this.props.form;
const { attribute, isViewMode } = this.state;
const index = 0;
return (
<div className="App">
<Row key={index} gutter={8}>
<Col span={6} offset={4}>
<Form.Item help="">
<Checkbox
checked={attribute.isActive}
disabled={isViewMode}
onChange={this.handleChangeAttributeActive}
value={attribute.name}
>
{attribute.name}
</Checkbox>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item help="">
{getFieldDecorator(`${attribute.name}`, {
message: attribute.attributeSendName,
rules: [{ required: attribute.isActive }]
})(<Input />)}
</Form.Item>
</Col>
</Row>
</div>
);
}
}
const WrappedApp = Form.create()(App);
const rootElement = document.getElementById("root");
ReactDOM.render(<WrappedApp />, rootElement);
根据您的需要更改此代码。