react-final-form with autocomplite component



>当我与反应最终表单数组连接时,我有动态表单并且从材料UI的Autocomplite组件出现问题,无法获取选定的项目值

这是表单代码

<Field
name={`${name}`.product}
list={products}
component={AutocompleteField}
label={'Products'}
/>
function ProductSelectField({list, label, dealer_id, stock_id, all_stocks, input, ...rest}) {
const {name, onChange, ...restInput} = input;
const [value, setValue] = useState([]);
const [inputValue, setInputValue] = useState('');
const getProducts = (event, newValue) => {
setValue(newValue);
}
return (
<Autocomplete
{...rest}
id="product"
options={list}
getOptionLabel={(option) => option.name}
defaultValue={list[0]}
onChange={getProducts}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
renderInput={(params) =>
<TextField
{...restInput}
{...params}
label={label}
variant="outlined"
/>
}
/>
);
}

没有任何额外的信息或代码框要关闭,似乎您没有调用输入的onChange钩来更新字段状态。在自动完成prop.onChange中,您正在调用getProducts钩子,而不是将值传递给onChange钩子的位置。

- const {name, onChange, ...restInput} = input; //delete
<TextField
- {...restInput} //delete
{...params}
label={label}
variant="outlined"
/>
// spread out the entire input prop into the Autocomplete
<Autocomplete
{...input}
{... rest of your props}
/>

这些关于 React-Final-Form 的文档向您展示了input道具传递的内容,并展示了它如何为您完成所有工作。

但是,我也从 material-ui 使用自动完成功能,并了解您希望同时控制本地状态。重构getProducts挂钩以更新两者。

const getProducts = (event, newValue) => {
setValue(newValue);
input.onChange(event); // the event will carry over because 'text' and 'select' inputs both return the 'event.target.value' without any extra logic for the Field component.
}

最新更新