为什么在 Ant Design 表单中不能正确验证自定义输入控件?

Cha*_*ire 2 javascript forms reactjs antd

我正在使用 Ant Design,但我在使用 Forms 时遇到了以下问题。

我有一个自定义组件,它用远程获取自动完成建议所需的代码包装了一个 antd AutoComplete:

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}
        />
    )
}
Run Code Online (Sandbox Code Playgroud)

但是当我以 antd 形式使用它时:

return (
    <Form
        {...formLayout}
        ref={this.formRef}
    >
        <Form.Item
            name={'product'}
            label={'Product'}
            rules={[{
                required: true
            }]}
        >
            <ProductComplete/>
        </Form.Item>
    </Form>
Run Code Online (Sandbox Code Playgroud)

当我因此let fieldsValue = await this.formRef.current.validateFields()在外部触发验证时:表单表现得好像字段中没有任何内容,并根据指定的验证规则通知用户该字段是必需的(即使自动完成中有文本)

但是,如果我将 AutoComplete 直接连接到包含 Form 的组件中,而不是将其打包为自己的组件(如上),它仍然可以正常工作!

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>
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

干杯!

Cha*_*ire 6

没关系我想通了!

我不知何故没有注意到Ant Design 网站上的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}
        />
    )
}
Run Code Online (Sandbox Code Playgroud)

现在工作正常。真的很明显。

干杯