React-获取功能组件中的组件名称

时间:2018-09-23 11:25:59

标签: reactjs

我希望在我的应用程序的每个组件上添加属性component-name =“ componentX”。我不想在创建组件时进行硬编码,而是想找到一种通用的方法来查找组件名称并将其设置在属性中。

我知道有displayName属性,但这仅用于类组件。

我有很多功能组件。我该如何实现?

谢谢!

1 个答案:

答案 0 :(得分:2)

如果包装子级,则可以访问select ID, Report_Month, sum(Total) as month_total, sum(sum(Total)) over (partition by ID order by report_month rows between 11 preceding and current row) as Running_Total from TOTALS_TABLE tt group by id, Report_Month; 以获取组件/函数名称。

这是一个小例子:

child.type.name
class LogNames extends React.Component {
  render() {
    const { children } = this.props;
    React.Children.forEach(children,child =>{
      console.log(child.type.name)
    });
    return children;
  }
}

class Child extends React.Component {
  render() {
    return <div>A Child</div>
  }
}

const Child2 = () => <div>Child 2</div>

class App extends React.Component {
  render() {
    return (
      <div>
        <LogNames>
          <Child/>
        </LogNames>
        <LogNames>
          <Child2 />
        </LogNames>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

刚刚注意到您也想在DOM上设置一个属性,所以我添加了另一个示例(打开devtools来查看属性):

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root" />
class WithNameAttr extends React.Component {

  componentDidMount(){
    const {children} = this.props;

    // get a ref to the current node
    const node = ReactDOM.findDOMNode(this);

    // force and return a signle child
    const child = React.Children.only(children);

    // set name attribute (if available) 
    const name = child.type.name;
    name && node.setAttribute('component-name', name);
  }

  render() {
    return this.props.children;
  }
}

class Child extends React.Component {
  render() {
    return <div>A Child</div>
  }
}

const Child2 = () => <div>Child 2</div>

class App extends React.Component {
  render() {
    return (
      <div>
        <WithNameAttr>
          <Child />
        </WithNameAttr>
        <WithNameAttr>
          <Child2 />
        </WithNameAttr>
        <WithNameAttr>
          <div>dom elemetns doesnt have names</div>
        </WithNameAttr>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);