【问题标题】:Getting name of all nested HOC wrappers and base component inside an HOC获取 HOC 内所有嵌套 HOC 包装器和基础组件的名称
【发布时间】:2019-08-30 23:41:26
【问题描述】:

我已经看到包和库能够console.log HOCs + 基本组件。由于以下原因,我对如何实现它感到非常困惑:

  • 类组件的名称定义为component.displayName
  • 功能组件有component.name
  • HOC 没有获取嵌套 HOC 和组件名称的标准方法

例如一个示例 HOC

function NamePrinter(Wrapped) {
  return (class Wrapper extends React.Component {
    componentWillReceiveProps() {
      console.log(`the name of this component is ${Wrapped.displayName || Wrapped.name}`)
    }
    render() {
      return <Wrapped {...this.props} />
    }
  })
}

据我所知,这是真的。例如,react-reduxgetting the name 有自己的约定,但这意味着我在搜索名称时只能“深入一层”。

如果我有一个这样包装的组件:

NamePrinter(connect(() => ({}), null)(withStyles({})(React.memo(MyComponent))))

我如何console.log 使用我的示例 HOC

connect(withStyles(React.memo(MyComponent)))

或类似的具有相同表现力的东西?

【问题讨论】:

    标签: reactjs high-order-component


    【解决方案1】:

    我能得到的最接近的算法。如前所述,没有标准的方法来公开包装的组件。对于material-ui,它被称为Naked,而react-reduxWrappedComponent。未优化算法

    // assuming material-ui and react-redux only
    function getDisplayName(component) {
        function getName(type) {
            let str = "";
            if (type.displayName) {
                str += "(" + type.displayName;
            } else if (type.name) {
                str += "(" + type.name;
            }
    
            if (type.Naked && getName(type.Naked)) {
                str += getName(type.Naked);
            } else if (type.WrappedComponent && getName(type.WrappedComponent)) {
                str += getName(type.WrappedComponent);
            } else if (type.render && getName(type.render)) {
                str += getName(type.render);
            } else if (typeof type === "string") {
                str += type;
            } else if (type.type && getName(type.type)) {
                str += getName(type.type);
            }
            return str;
        }
    
        let currStr = getName(component);
        const openParenCount = Array.from(currStr).filter(el => el === "(").length;
        const closeParenCount = Array.from(currStr).filter(el => el === ")").length;
        return (
            currStr + [...Array(openParenCount - closeParenCount)].map(el => ")").join("")
        )
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-13
      • 2020-10-29
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多