React hooks: How do I update state on a nested object with useState()?

前端 未结 6 815
一个人的身影
一个人的身影 2021-02-08 13:43

I have a component that receives a prop that looks like this:

const styles = {
    font: {
        size: {
            value: \'22\',
            unit: \'px\'
           


        
6条回答
  •  盖世英雄少女心
    2021-02-08 14:07

    You need to use spread syntax to copy the font object properties too. Also while trying to update current state based on previous, use the callback pattern

     { 
        setStyle(prevStyle => ({
            ...prevStyle,
            font: { ...prevStyle.font, align: event.target.value }
        }));
        console.log(style);
      }}
    />
    

提交回复
热议问题