cod*_*aff 27 javascript reactjs react-jsx
如何将没有价值的道具传递给反应组件?
<SomeComponent disableHeight> {/* here */}
{({width}) => (
<AnotherComponent
autoHeight {/* and here */}
width={width}
height={300}
{...otherProps}
/>
)}
</SomeComponent>
Run Code Online (Sandbox Code Playgroud)
注意 - 没有为这些道具指定默认道具值.
我似乎无法找到任何引用,但通过观察true默认情况下分配给它们的属性的值.
Chr*_*ris 53
传递的内容被编译器解释为布尔属性.在编写纯HTML时也是如此; 没有值的属性被解释为布尔值true.由于JSX是用于编写HTML的语法糖,因此它具有相同的行为是有道理的.
官方的React文档包含以下内容:
布尔属性
这通常在使用HTML表单元素时出现,其中包含disabled,required,checked和readOnly等属性.省略属性的值会导致JSX将其视为true.要传递false,必须使用属性表达式.
// 这两个在JSX中是等效的,用于禁用按钮
Run Code Online (Sandbox Code Playgroud)<input type="button" disabled />; <input type="button" disabled={true} />;// 这两个在JSX中是等效的,因为没有禁用按钮
Run Code Online (Sandbox Code Playgroud)<input type="button" />; <input type="button" disabled={false} />;
JSX:
<div>
<Component autoHeight />
<AnotherComponent autoHeight={null} />
</div>
Run Code Online (Sandbox Code Playgroud)
JS:
React.createElement(
"div",
null,
React.createElement(Component, { autoHeight: true }),
React.createElement(AnotherComponent, { autoHeight: null })
);
Run Code Online (Sandbox Code Playgroud)
在这里查看这个babel demo .
正如ctrlplusb所说,如果你想传递一个"空道具",你可以简单地给它值null或甚至undefined.
所以你可以这样做:
<SomeComponent disableHeight={null}>
{({width}) => (
<AnotherComponent
autoHeight={null}
width={width}
height={300}
{...otherProps}
/>
)}
</SomeComponent>
Run Code Online (Sandbox Code Playgroud)
虽然我会注意到,把它当作undefined是可能完全不必要的,因为阅读this.props.autoHeight从AnotherComponent总会给你undefined,如果你不管通过明确其作为autoHeight={undefined}或不尽然.null在这种情况下,传递可能更好,因为您通过声明它具有......"无值"(即null)的值来明确传递道具.
是的,JSX看到的属性没有=因为布尔值为true.
一种选择是简单地设置空值:
<Foo name="Bob" surname={null} />
Run Code Online (Sandbox Code Playgroud)
您还可以通过对象动态构建属性包,并仅在需要时添加属性.例如:
render() {
const propBag = {
width: width,
height: 300
};
if (someCondition) {
propBag.something = 'bob';
}
return (
<FooComponent {...propBag} {..otherProps} />
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16843 次 |
| 最近记录: |