[英]How to pass props without value to component
如何將沒有價值的道具傳遞給反應組件?
<SomeComponent disableHeight> {/* here */}
{({width}) => (
<AnotherComponent
autoHeight {/* and here */}
width={width}
height={300}
{...otherProps}
/>
)}
</SomeComponent>
注意 - 沒有為這些道具指定默認道具值。
我似乎無法找到任何引用,但通過觀察這些屬性的值,默認情況下它們被賦值為true
。
傳遞的內容被編譯器解釋為布爾屬性。 在編寫純HTML時也是如此; 沒有值的屬性被解釋為布爾值true
。 由於JSX是用於編寫HTML的語法糖,因此它具有相同的行為是有道理的。
官方的React文檔包含以下內容:
布爾屬性
這通常在使用HTML表單元素時出現,其中包含disabled,required,checked和readOnly等屬性。 省略屬性的值會導致JSX將其視為true。 要傳遞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 demo。
正如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
)來顯式傳遞prop。
是的JSX看到沒有=
屬性是一個布爾值true。
一種選擇是簡單地設置空值:
<Foo name="Bob" surname={null} />
您還可以通過對象動態構建屬性包,並僅在需要時添加屬性。 例如:
render() {
const propBag = {
width: width,
height: 300
};
if (someCondition) {
propBag.something = 'bob';
}
return (
<FooComponent {...propBag} {..otherProps} />
);
}
<Amp.AmpAccordion animate="">
上面鏈接中的副本+粘貼:
具有空字符串的任何屬性將在沒有值的情況下呈現到DOM中。
W3C相關文檔: https : //www.w3.org/TR/html5/syntax.html#elements-attributes
空屬性語法
只是屬性名稱。 該值隱含為空字符串。在以下示例中,disabled屬性以空屬性語法給出:
<輸入已禁用>如果使用空屬性語法的屬性后跟另一個屬性,則必須有一個空格字符將兩者分開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.