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

前端 未结 6 816
一个人的身影
一个人的身影 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

    This is your mistake

    setStyle({
        ...style,
        font: { align: event.target.value } // This code replace the font object
    });
    

    To preserve the all font object values, you can do like this

    const onChange = (event) => {
        const s = {...style};
        s.font.align = event.target.value;
        setStyle(s);
    }
    

    Or

    const onChange = (event) => {
        setStyle({ 
            ...style,
            font: {
                ...style.font, // Spread the font object to preserve all values
                align: event.target.value
            }
        });
    }
    

提交回复
热议问题