[英]How to overwrite default props of a higher order component?
我有一個具有以下默認道具的高級商品:
defaultProps = {
className: null,
duration: 400
};
現在,我有另一個組件,例如<InnerBox />
,它正在使用此高階組件作為擴展。 如何從<InnerBox />
內部覆蓋我的高階組件中的defaultProps值?
當我嘗試從<InnerBox />
內部執行相同操作時:
static defaultProps = {
className: "classnameforthiscomponent"
duration: 300
};
沒用 我為定義其他默認組件的原因是因為此組件是由路由器生成的(在另一個文件上設置的),所以我無法從外部將道具傳遞給它,如下所示:
<InnerBox
duration={300}
className="classnameforthiscomponent"
/>
我該如何解決?
如何從
<InnerBox />
內部覆蓋我的高階組件中的defaultProps值?
imo。 你不能,因為<InnerBox />
不知道它是如何調用。
一旦獲得props
,就不知道它們來自何處。 作為道具傳遞給HOC或defaultProps或其他; 至少那是應該的。
您可以提供將defaultProps
與要包裝為此HOC的組件一起傳遞的功能
const wrapper = (component, defaultProps) => // your HOC
或者您的HOC可以使用包裝組件的defaultProps
//maybe like
const wrapper = (component) => {
return class {
static defaultProps = Object.assign({}, HOC.defaultProps, component.defaultProps);
}
}
或者,您或者您根本不使用defaultProps
。
要么:
render(){
let props = {
...defaults,
...InnerBox.defaultProps,
...this.props
}
return <InnerBox {...props} />;
}
或者,您只是通過props
,不要使用HOC.defaultProps
但是現在包裝的組件必須處理可能未定義的props。
InnerBox
無法處理包裝的組件。HOC需要考慮包裝的組件。
由於您的高階框取決於InnerBox,因此應將其導入
import InnerBox from './path'
class HigherOrderBox {
static defaultProps = {
// here you can destruct InnerBox.defaultProps
...InnerBox.defaultProps,
// or just a single property,
duration: InnerBox.defaultProps.duration
// and you can also have
additionalProperty: true
}
}
如果不需要其他屬性,則可以定義
static defaultProps = InnerBox.defaultProps;
您可以將高階組件包裝在函數內部,並在其中傳遞道具:
export default (outerProps) => {
return (ComposedComponent) => {
class MyHOC extends Component {
// inside stuff of HOC
}
MyHOC.defaultProps = {
className: outerProps.className || null,
duration: outerProps.duration || null
}
return MyHOC;
}
}
而且,將您的HOC與InnerBox一起使用時:
MyHOC({
className: 'my-custom-class',
duration: 600
})(InnerBox)
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.