cod*_*mon 17 javascript destructuring reactjs
我有一个组件,它接收一个看起来像这样的道具:
const styles = {
font: {
size: {
value: '22',
unit: 'px'
},
weight: 'bold',
color: '#663300',
family: 'arial',
align: 'center'
}
};
Run Code Online (Sandbox Code Playgroud)
我正在尝试更新该align属性,但是当我尝试更新该对象时,我最终仅用该align属性替换了整个对象。
这就是我更新它的方式:
const { ...styling } = styles;
const [style, setStyle] = useState(styling);
return (
<RadioButtonGroup
onChange={(event) => {
setStyle({ ...style, font: { align: event.target.value } });
console.log(style);
}}
/>);
Run Code Online (Sandbox Code Playgroud)
当我 console.logstyle我刚{"font":{"align":"left"}}回来。我希望看到整个对象的更新值align。我是解构的新手,所以我在这里做错了什么?
Shu*_*tri 28
您还需要使用扩展语法来复制字体对象属性。此外,在尝试根据以前更新当前状态时,请使用回调模式
<RadioButtonGroup
onChange={(event) => {
setStyle(prevStyle => ({
...prevStyle,
font: { ...prevStyle.font, align: event.target.value }
}));
console.log(style);
}}
/>
Run Code Online (Sandbox Code Playgroud)
这是你的错误
setStyle({
...style,
font: { align: event.target.value } // This code replace the font object
});
Run Code Online (Sandbox Code Playgroud)
要保留所有font对象值,您可以这样做
const onChange = (event) => {
const s = {...style};
s.font.align = event.target.value;
setStyle(s);
}
Run Code Online (Sandbox Code Playgroud)
或者
const onChange = (event) => {
setStyle({
...style,
font: {
...style.font, // Spread the font object to preserve all values
align: event.target.value
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果嵌套对象中有多个值,请尝试以下方法:
setPost({
...post,
postDetails: {
...post.postDetails,
[event.target.name]: event.target.value,
},
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24509 次 |
| 最近记录: |