【问题标题】:react-final-form with autocomplite component带有自动完成组件的 react-final-form
【发布时间】:2020-06-16 05:33:38
【问题描述】:

当我与 react-final-form-arrays 连接时,我有我的动态表单,并且来自 material-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"
                />
            }
        />
    );
}

【问题讨论】:

    标签: reactjs react-final-form react-final-form-arrays


    【解决方案1】:

    如果没有任何额外的信息或代码框,您似乎没有调用输入的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}
    />
    
    

    These Docs on 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.
        }
    

    【讨论】:

      猜你喜欢
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 2017-07-10
      相关资源
      最近更新 更多