我有一个包含许多子节点的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获取子名称.
- 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>