控制材料UI输入不工作



我创建了一个用于编辑记录的模态,但我似乎无法控制输入。我已经尝试了我在网上看到的关于控制材质UI输入字段的一切,但每次我打开编辑模式时,我都会得到这个错误:"警告:组件正在将非受控输入更改为受控输入。这很可能是由于值从未定义变为已定义的值,而这是不应该发生的。决定在组件的生命周期内使用受控或非受控输入元素。">

我已经添加了defaultValue的输入,但它似乎没有帮助。我如何控制这些输入并停止这个错误?

editModal.js

<Form onSubmit={handleSubmit} open={openModal}> 
<Grid container spacing={0}>
<Grid item xs={6}>
<Input
name="tankName"
label="Tank Name"
value={item.tankName}
onChange={handleInputChange}
error={errors.tankName}
/>
</Grid>
<Grid item xs={6}>
<Checkbox
label="Allow Corrective Actions"
name="allowCorActionRecom"
value={item.allowCorActionRecom}
onChange={handleInputChange}
/>
</Grid>
</Grid>
<Grid>
<div>
<Button
type="submit"
text="Submit"
onClick={editRecord}
/>
<Button
text="Cancel" 
onClick={()=>{setOpenModal(false)}}
/>
</div>
</Grid>
</Form>
)}

input.js

export default function Input(props) {
const { error=null, label, name, onChange, value, ...other } = props;
return (
<TextField
label={label}
name={name}
value={value}
defaultValue=''
onChange={onChange}
{...other}
{...(error && {error:true,helperText:error})}
/>
)
}

checkbox.js

export default function Checkbox(props) {
const { name, label, value, onChange } = props;
const convertToDefEventPara = (name, value) => ({
target: {
name, value
}
})
return (
<FormControl>
<FormControlLabel
control={<MuiCheckbox
name={name}
color="primary"
checked={value}
defaultValue="unchecked"
onChange={e => onChange(convertToDefEventPara(name, e.target.checked))}
/>}
label={label}
/>
</FormControl>
)
}

formFuctions.js

export function FormFunctions(validateOnChange = false, validate) {
const [values, setValues] = useState('');
const [errors, setErrors] = useState({});
const handleInputChange = e => {
const { name, value } = e.target
setValues({
...values,
[name]: value
})
if (validateOnChange)
validate({ [name]: value })
};
return {errors, handleInputChange, setErrors, setValues, values}
};

而不是使用

value={value}
defaultValue=''
and
checked={value}
defaultChecked={false}

我使用一个三进制来强制输入有值,这似乎已经纠正了我的问题。

value={value === undefined ? '' : value}
and
checked={value === undefined ? false : value}

到目前为止,我还没有发现这个解决方案有任何问题。

最新更新