【问题标题】:How do I decorate a react component and all its children?如何装饰一个反应组件及其所有子组件?
【发布时间】:2017-12-03 22:03:36
【问题描述】:

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')
);

【问题讨论】:

    标签: javascript reactjs decorator react-jsx ecmascript-next


    【解决方案1】:

    要理解递归,你必须先理解递归!

    除此之外,我过去成功使用过这个 sn-p :

    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,它就会完成剩下的工作。在这个 sn-p 中,我们只需为所有子节点添加一个 DECORATED 布尔值。

    【讨论】:

    • 我给你 +1 是因为我相信这会奏效,并感谢你花时间回答这个问题。话虽如此;我正在寻找一个使用 es7 装饰器而不是自定义装饰概念的答案。干杯!
    • 你可能想更新你的问题,你不是在装饰组件树,你是在装饰渲染函数,我仍然认为这可以用同样的方式完成,但我还不够有 ES7 经验才能真正提出答案
    猜你喜欢
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 2019-04-27
    • 2014-09-02
    • 1970-01-01
    • 2020-03-11
    • 2019-05-09
    • 1970-01-01
    相关资源
    最近更新 更多