我希望在我的应用程序中的每个组件上添加属性 component-name="componentX"。我不想在创建组件时对其进行硬编码,而是想找到一种通用方法来查找组件名称并将其设置在属性中。
我知道有 displayName 属性,但它仅适用于类组件。
我有很多功能组件。我怎样才能实现它?
谢谢!
如果您包装子项,您可以访问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);Run Code Online (Sandbox Code Playgroud)
<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" />Run Code Online (Sandbox Code Playgroud)
刚刚注意到您还想在 DOM 上设置一个属性,所以我添加了另一个示例(打开 devtools 以查看属性):
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);Run Code Online (Sandbox Code Playgroud)
<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"/>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8548 次 |
| 最近记录: |