我正在使用Ant Design,我在使用表单时遇到了以下问题。
我有一个自定义组件,它用远程获取自动完成建议所需的代码包装了一个 antd 自动完成:
const ProductComplete = () => {
const [value, setValue] = React.useState('')
const [options, setOptions] = React.useState([])
const onSearch = searchText => {
fetchProductsFromServer(searchText)
.then(options => options.map(o => ({value: o})))
.then(options => setOptions(options))
}
const onChange = data => {
setValue(data)
}
return (
<AutoComplete
value={value}
options={options}
onSearch={onSearch}
onChange={onChange}
/>
)
}
但是当我以 antd 形式使用它时:
return (
<Form
{...formLayout}
ref={this.formRef}
>
<Form.Item
name={'product'}
label={'Product'}
rules={[{
required: true
}]}
>
<ProductComplete/>
</Form.Item>
</Form>
当我因此在外部触发验证时:let fieldsValue = await this.formRef.current.validateFields()
表单的行为就好像字段中没有任何内容一样,并向用户发出信号,根据指定的验证规则需要该字段(即使自动完成中有文本(
但是,如果我将自动完成直接连接到保存表单的组件中,而不是将其打包为自己的组件(如上所述(,它工作正常!
return (
<Form
{...formLayout}
ref={this.formRef}
>
<Form.Item
name={'product'}
label={'Product'}
rules={[{
required: true
}]}
>
<AutoComplete
value={this.state.product}
options={this.state.products}
onSearch={(searchText) => this.onSearchProducts(searchText)}
onChange={(value) => this.onChange(value)}
/>
</Form.Item>
</Form>
任何想法为什么会这样?
干杯!
没关系,我想通了!
我不知何故没有注意到蚂蚁设计网站上的 https://ant.design/components/form/#components-form-demo-customized-form-controls 部分。
我只需要向自定义组件传递一个受控的value
属性和onChange
事件,因此:
const ProductComplete = ({value = '', onChange}) => {
const [products, setProducts] = React.useState([])
const onSearch = searchText => {
fakeFetch(searchText)
.then(options => options.map(o => ({value: o})))
.then(options => setProducts(options))
}
const handleChange = (value) => {
if (onChange) {
onChange(value)
}
}
return (
<AutoComplete
value={value}
options={products}
onSearch={onSearch}
onChange={handleChange}
/>
)
}
现在工作正常。真的很明显.
干杯