[英]React functional props
讓我先給你看一個例子:
<List hidden={this.state.hideList} />
對於這種情況,我希望hidden
道具以下列方式起作用:如果value為true –隱藏組件,否則顯示。 List
不應該知道這個道具。
我對React內部知識了解不多,但這似乎是可能的。 我們只需要擴展React.Component
類。 也許將所有功能性的道具擴展到全球並不是一個好主意,但是在頂部放置這樣的東西會很好:
import { ReactComponent } from 'react'
import extend, { hidden } from 'react-functional-props'
const Component = extend(ReactComponent, hidden)
它使我想起了Angular.js中的指令,但是在這里我們可以將它們組合起來。
您可以只在render方法中返回null
或undefined
來阻止它呈現,或使用條件類將其隱藏,如下所示:
return !this.state.hideList && <List />;
關於
反應功能道具
在React中,您可以使用高階組件(HOC)來實現所需的功能,例如:
const Hideable = Component => (props) => {
const { isHidden, ...otherProps } = props;
return !isHidden && (<Component {...otherProps} />);
};
const HideableList = Hideable(List);
...
return (
<div>
<HideableList isHidden={this.state.hideList} /> // The isHidden props is handled by the HOC
</div>
);
但是對於這樣的簡單用例,我認為只處理父組件中的隱藏和顯示要清晰得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.