我有一个TextField,它在更改时使用useState更新状态。我面临一个问题,即状态更改后整个组件都将重新呈现,我希望仅TextField会发生更改。
const Uploader = ({ onUploadComplete }) => {
const [fields, setFields] = useState({});
const handleName = (event) => {
const { name, value } = event.target;
setFields((fields) => ({
...fields,
[name]: { value: value },
}
<React.Fragment>
<Grid item xs={4}>
<Card>{console.log('Card Media Rendered')}</Card>
</Grid>
<Grid item xs={8}>
<FormControl fullWidth>
<TextField
value={fields[file.id]?.value || ''}
onChange={handleName}
/>
</FormControl>
</Grid>
</React.Fragment>
}
答案 0 :(得分:0)
您需要像这样在功能组件内部移动useState
:
const Uploader = ({ onUploadComplete }) => {
const [fields, setFields] = useState({});
const handleName = (event) => {
const { name, value } = event.target;
setFields((fields) => ({
...fields,
[name]: { value: value },
}))
}
return (
<React.Fragment>
<Grid item xs={4}>
<Card>{console.log('Card Media Rendered')}</Card>
</Grid>
<Grid item xs={8}>
<FormControl fullWidth>
<TextField
value={fields[file.id]?.value || ''}
onChange={handleName}
/>
</FormControl>
</Grid>
</React.Fragment>
)
}
您的组件确实重新呈现,因为它所依赖的变量不在反应范围内。因此它不能仅触发对Textfield的更新