antd小技巧
kingcwt2021-1-19前端react antd
设置Form.Item的name属性
不管Form.Item下有多少层嵌套元素。如果想要给表单设置name并操作这个表单,只需要在表单外层设置Form.Item 加上nostyle属性
<Form.Item label="相似度算法" labelCol={{ span: 8 }}>
<Row>
<Col span={13}>
<Form.Item noStyle name="similarity">
<Select placeholder="默认LCS" disabled={lookDisable}>
<Select.Option value="wm_distance">wmdistance</Select.Option>
<Select.Option value="lcs">LCS</Select.Option>
<Select.Option value="weight_lcs">加权LCS</Select.Option>
<Select.Option value="levenshtein">Levenshtein距离</Select.Option>
</Select>
</Form.Item>
</Col>
<Col span={2} offset={1}>
<Tooltip placement="topLeft" title="下拉框选">
<div className="flex">
<QuestionCircleOutlined />
</div>
</Tooltip>
</Col>
</Row>
</Form.Item>
通过
form.getFieldsValue()
来获取所有的name值,当然你要对form表单绑定form
通过const [form] = Form.useForm()
;
import {Form} from 'antd';
const submit = () =>{
console.log(form.getFieldsValue(),'form-name')
}
const demo = ()=>{
const [form] = Form.useForm();
return(<Form form={form}></Form>)
}
一个表单改变去校验另一个表单,表单校验
只需要给input设置rules.
validator
校验,当select改变的时候通过form.validateFields(['include_keyword'])}
来手动触发校验即可
<Form.Item label="标题必须包含关键字" labelCol={{ span: 8 }}>
<Row>
<Col span={13}>
<Form.Item
name="include_keyword"
noStyle
rules={[
{
validator: (_, val) => {
if (!titleSelectState) return Promise.resolve();
const upVal = form.getFieldValue(['titleSelect']);
if (!upVal && val.length > 0) {
return Promise.reject('请选择匹配度');
} else {
return Promise.resolve();
}
},
},
]}
>
<Input
placeholder="多个关键字请用空格"
onChange={changeInclude_keyword}
disabled={lookDisable}
name="ccc"
/>
</Form.Item>
</Col>
<Col span={10} offset={1}>
<Form.Item name="titleSelect" noStyle rules={modelRules4}>
<Select
placeholder="匹配模式"
disabled={lookDisable}
onChange={() => form.validateFields(['include_keyword'])}
>
<Select.Option value="精确匹配">精确匹配</Select.Option>
<Select.Option value="wmdistance">wmdistance</Select.Option>
<Select.Option value="LCS">LCS</Select.Option>
<Select.Option value="加权LCS">加权LCS</Select.Option>
<Select.Option value="Levenshtein距离">Levenshtein距离</Select.Option>
</Select>
</Form.Item>
</Col>
</Row>
</Form.Item>