繁体   English   中英

React & Typescript:嵌套的 defaultProps 深度合并

[英]React & Typescript: nested defaultProps deep merge

我正在创建一个 React & Typescript 组件,需要定义一些默认道具,这些道具是具有嵌套数据的对象。 这是我的组件的简化示例:

type Props = {
    someProp: string,
    user: {
        blocked: boolean,
        active: boolean
    }
}

export const UserPage: React.FC<Props> = props => {
    (...)
};

然后我像这样定义默认道具:

const defaultProps: Props = { 
    user: {
        blocked: true
    }
}

UserPage.defaultProps = defaultProps

问题是,如果使用以下道具调用我的组件

<UserPage user={{ active: true }}/>

默认道具中的用户 object 将被完全覆盖。

使用嵌套数据声明和合并 props 和 default props 的最佳方法是什么?

您可以使用

const propsWithDefaults = Object.assign(defaultProps, props);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM