简体   繁体   中英

'children' is not defined - in React class component

So, I have a stateless component that uses 'React.Children.map()' that I want to turn into a class component to add it a state, but since I cannot (that I know about) pass {children} as an property anymore, I get the error saying that 'children' is not defined. How can I define children?

Original stateless component:

import React from 'react';

const Tabs = ({ children }) => (
  <div className="tabsPanel" onClick={clickHandler}>
    {React.Children.map(children, child =>
      React.cloneElement(child, { clickHandler: () => console.log('clicked') })
    )}
  </div>
);

export default Tabs;

class component:

import React, { Component } from 'react';

class Tabs extends Component {
  render() {
    return (
      <div className="tabsPanel">
        {React.Children.map(children, child =>
          React.cloneElement(child, {
            clickHandler: () => console.log('clicked', child.props.children),
          })
        )}
      </div>
    );
  }
}

export default Tabs;

You have not defined the children variable in your render method. The props are given as first argument to a function component, but they are available at this.props in a class component.

class Tabs extends Component {
  render() {
    return (
      <div className="tabsPanel">
        {React.Children.map(this.props.children, child =>
          React.cloneElement(child, {
            clickHandler: () => console.log('clicked', child.props.children),
          })
        )}
      </div>
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM