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

前端 未结 6 817
一个人的身影
一个人的身影 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 13:51

    Your code for default useState is invalid. You should write like below for default useState:

      const { ...styling } = styles;
      const [style, setStyle] = useState({ styling }); // styling should be use in {}
    
    return (
             {
                setStyle({
                  ...styling,
                  font: { ...styling.font, align: event.target.value }
                });
                console.log(style);
              }}
            />);
    

    Demo: check this demo with console.log.

提交回复
热议问题