2017-06-30 23 views
2

https://jsfiddle.net/69z2wepo/81913/我如何裝飾反應組件及其所有孩子?

我正在裝飾一個組件樹並向我的組件添加一些元數據。在頂層組件(A)中出色地工作;但如果我嘗試裝飾我的子組件(註釋掉,但未註釋說明問題) - 渲染鏈斷裂並且傳遞的道具無法正確渲染(或根本不渲染)。有沒有人有任何見解 - 我已附上上面的小提琴。

var dec = (t, k, d) => { 
    console.log('hello decoration') 
    var el = React.cloneElement(d.value(), {'label': 'my-component-label'}) 
    return {value:() => el} 
} 

class B extends React.Component{ 
    constructor(props) { 
    super(props) 
    } 
    //@dec 
    render() { 
    return <div> 
     {this.props.data} 
    </div> 
    } 
} 
class A extends React.Component{ 
    constructor(props) { 
    super(props) 
    } 

    @dec 
    render() { 
    return <div> 
     <B data={99 + 101}/> 
    </div> 
    } 
} 

ReactDOM.render(
    <A/>, 
    document.getElementById('container') 
); 

回答

1

爲了理解遞歸,你必須先了解遞歸!這且不說,我已經成功地在過去使用這個片段

recursiveCloneChildren(children) { 
    return React.Children.map(children, (child) => { 
    let childProps = {}; 

    if (!child || !child.props) { 
     return child; 
    } 
    childProps.DECORATED = true; 
    childProps.children = this.recursiveCloneChildren(child.props.children); 
    return React.cloneElement(child, childProps); 
    }); 
} 

只要給它一個組件的this.props.children,它會做休息。在這個片段中,我們簡單地爲所有孩子添加一個DECORATED布爾值。

+0

我給你+1,因爲我相信這會起作用,並感謝你花時間回答這個問題。話雖如此;我正在尋找一個使用es7裝飾器而不是自定義裝飾概念的答案。乾杯! – Conqueror

+0

你可能想更新你的問題,然後,你不裝飾組件樹,你正在裝飾渲染功能,我仍然認爲這可以用同樣的方式完成,但是我沒有足夠的ES7經驗來真正建議回答 – Patrick

相關問題