您传递的内容被编译器解释为布尔属性。在编写纯 HTML 时也是如此;没有值的属性被解释为布尔值true。由于 JSX 是编写 HTML 的语法糖,因此它具有相同的行为是有道理的。
官方React documentation有以下内容:
布尔属性
这通常在使用带有属性的 HTML 表单元素时出现
像 disabled、required、checked 和 readOnly。
省略属性的值会导致 JSX 将其视为 true。到
pass false 必须使用属性表达式。
// 这两个在 JSX 中等效用于禁用按钮
<input type="button" disabled />;
<input type="button" disabled={true} />;
// 这两个在 JSX 中是等价的,因为没有禁用按钮
<input type="button" />;
<input type="button" disabled={false} />;
示例
JSX:
<div>
<Component autoHeight />
<AnotherComponent autoHeight={null} />
</div>
JS:
React.createElement(
"div",
null,
React.createElement(Component, { autoHeight: true }),
React.createElement(AnotherComponent, { autoHeight: null })
);
查看 babel 演示,here。
解决方案
正如 ctrlplusb 所说,如果你想传递一个“空道具”,你可以简单地给它 null 甚至 undefined 的值。
所以你可以这样做:
<SomeComponent disableHeight={null}>
{({width}) => (
<AnotherComponent
autoHeight={null}
width={width}
height={300}
{...otherProps}
/>
)}
</SomeComponent>
虽然我会注意到将其传递为undefined 可能完全没有必要,因为从AnotherComponent 读取this.props.autoHeight 将始终为您提供undefined,无论您是否明确将其传递为autoHeight={undefined} 或根本不传递。在这种情况下传递 null 可能会更好,因为您通过声明它的值...“无值”(即 null)来明确传递道具。