我有一个包含许多子项的 React (15.5.4) 组件,其中一些是 HTML 元素,一些是其他 React 组件。
我正在使用服务器渲染并且需要在服务器和客户端上有相同的行为。客户端将使用 React 的生产构建。
我需要遍历子组件并确定特定类型的 React 组件。所以我的第一个想法是使用 React.Children.forEach()
进行迭代并查找组件名称。
React.Children.forEach(this.props.children, child => {
console.log('name =', child.name)
})
似乎 child.name
和 child.displayName
不存在。
现在,child.type
存在了,它要么是一个字符串(对于 HTML 元素),如 "ul"
,要么是一个函数(对于 React 组件)。
当它是一个函数时,我可以像这样使用 lodash/get
const type = get(child, 'type.name', '')
来获取组件姓名。 但是,这似乎只在服务器上有效,而不是在客户端生产构建中,它返回一个字符串:"t"
。看起来开发版本使用我的组件名称作为函数,但生产版本将其重命名为 t()
。所以我不能使用 child.type.name
。
我如何:
- 遍历子组件并识别特定类型的组件..?
- 哪个在开发和生产 React 构建中都有效..?
最佳答案
您可以在属性 displayName
中设置组件的名称。如果您使用的是 ES6 类,则可以将名为 displayName
的静态属性设置到组件的类中。然后,您将能够使用 child.type.displayName
获取 child 的名字。
const FirstChild = ({ name }) => <li>{name}</li>;
FirstChild.displayName = 'FirstChild';
const SecondChild = ({ name }) => <li>{name}</li>;
SecondChild.displayName = 'SecondChild';
class ThirdChild extends React.Component {
static displayName = 'ThirdChild';
render() {
return (
<li>{this.props.name}</li>
);
}
}
class Parent extends React.Component {
componentDidMount() {
React.Children.forEach(this.props.children, child => {
console.log('name =', child.type.displayName);
})
}
render() {
return (
<ul>{this.props.children}</ul>
);
}
}
class App extends React.Component {
render() {
return (
<Parent>
<FirstChild name='1st child value' />
<SecondChild name='2nd child value' />
<ThirdChild name='3rd child value' />
</Parent>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
<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="app"></div>
关于javascript - ReactJS - React.Children.forEach - 我可以获得子组件名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43913054/