[英]Is it possible to achieve something like HOC with classes - without classes in React?
我想做類似的事情:
<SomeProvider showConfirm={showConfirm}>
{props.showConfirm()
? (<confirmActionComponent />)
: (<chooseActionComponent />)}
</SomeProvider>
在chooseActionComponent
內部,我希望能夠訪問showConfirm
或深度嵌套的子組件中的另一個值,以更新父組件中的某些值並顯示confirmActionComponent
。
我知道如何使用傾向於涉及到this
並在某些時候bind
class
來實現這一點,我寧願避免這種情況。
有沒有辦法使用純函數/組件來完成類似的事情? 還希望將其保留在Redux商店之外。
如果只想訪問showConfirm
,則可以將其傳遞給子級:
<SomeProvider showConfirm={showConfirm}>
{props.showConfirm()
? (<confirmActionComponent />)
: (<chooseActionComponent showConfirm={showConfirm} />)}
</SomeProvider>
請注意以下從React文檔引用到繼承的引用:
在Facebook,我們在成千上萬的組件中使用React,但還沒有找到建議創建組件繼承層次結構的用例。
無論如何,我可能會對您有一個非常骯臟的技巧...使用ref
...
const Child = () =>
<div ref={(self) => {
// get ReactDOMNode on stateless component
const ReactDOMNode = self[Object.keys(self).filter((key) =>
/__reactInternalInstance/g.test(key))[0]];
// access parent props
console.dir(ReactDOMNode
._hostParent
._currentElement
._owner
._currentElement
.props);
}}></div>;
注意:不建議這樣做,我也不建議這樣做。 我建議您簡單地將所需的父母道具傳遞給孩子。
<SomeProvider showConfirm={showConfirm}>
{props.showConfirm()
? (<confirmActionComponent />)
: (<chooseActionComponent showConfirm={showConfirm} />)}
</SomeProvider>
在您的chooseActionComponent
您可以:
const chooseActionComponent = ({parentProps: {showConfirm}}) =>
<div>{showConfirm}</div>;
您不必使用ES6類來創建React內容。 如果您希望避免重復使用bind
來確保方法的正確作用域(使用this.setState
/ this.props
),則可以恢復使用React API幫助器函數 ( 請參閱不帶ES6的React )。
您可以專門使用: React.createClass用於創建React類和HOC 。 再次,只是再次重申這一點:使用此替代語法會autobind this
給你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.