gpt4 book ai didi

javascript - 如何将没有值的 props 传递给组件

转载 作者:行者123 更新时间:2023-12-03 12:59:15 24 4
gpt4 key购买 nike

如何将没有值的 prop 传递给 React 组件?

<SomeComponent disableHeight> {/* here */}
{({width}) => (
<AnotherComponent
autoHeight {/* and here */}
width={width}
height={300}
{...otherProps}
/>
)}
</SomeComponent>

注意 - 没有为这些 Prop 指定默认 Prop 值。

我似乎找不到任何相关引用,但通过观察这些属性的值,它们默认分配为 true

最佳答案

编译器将您传递的内容解释为 bool 属性。编写纯 HTML 时也是如此;没有值的属性被解释为 bool 值 true。由于 JSX 是一种用于编写 HTML 的语法糖,因此它具有相同的行为是有道理的。

官方React documentation具有以下内容:

Boolean Attributes

This often comes up when using HTML form elements, with attributes like disabled, required, checked and readOnly. Omitting the value of an attribute causes JSX to treat it as true. To pass false an attribute expression must be used.

// These two are equivalent in JSX for disabling a button

<input type="button" disabled />;
<input type="button" disabled={true} />;

// And these two are equivalent in JSX for not disabling a button

<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 所说,如果你想传递一个“空 prop”,你可以简单地给它赋值 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)来显式传递该 prop。

关于javascript - 如何将没有值的 props 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37828543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com