Javascript React.js - 默认 prop 不使用,传递 `null`

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34809178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:52:46  来源:igfitidea点击:

React.js - default prop is not used with `null` is passed

javascriptreactjscomponents

提问by Kosmetika

I have default props in my React component:

我的 React 组件中有默认道具:

PropertyTitleLabel.defaultProps = {
    bedrooms: 1,
    propertyType: 'flat'
};
PropertyTitleLabel.propTypes = {
    bedrooms: PropTypes.number,
    propertyType: PropTypes.string
};

But when I'm passing nullto bedroomslike:

但是当我传递nullbedrooms喜欢时:

const bedrooms = null; // in real world API returns `null`
<Component bedrooms={bedrooms} />

It's not replaced with default prop :( Any ideas?

它没有被默认道具取代:(有什么想法吗?

回答by Jap Mul

You can change the nullvalue to undefinedto use the default value.

您可以将null值更改undefined为使用默认值。

<Component bedrooms={bedrooms || undefined} />

回答by Balthazar

I think there's a distinction between nulland undefinedthat is made when dealing with the defaultProps. The nullvalue could be intended behavior and thus isn't replaced by your defaults, while undefinedis not and will be replaced.

我觉得有区别null,并undefined与打交道时即发defaultProps。该null值可能是预期行为,因此不会被您的默认值替换,而undefined不会并且将被替换。

As stated in the docs

如文档中所述

[...] used to ensure that this.props.value will have a value if it was not specified by the parent component.

[...] 用于确保 this.props.value 将具有一个值,如果它不是由父组件指定的。

Here is a related issue.

这是一个相关的问题