未定义'children'-在React类组件中

时间:2019-04-15 09:53:34

标签: javascript reactjs children

因此,我有一个使用'React.Children.map()的无状态组件,我想将其转换为类组件以为其添加状态,但是由于我(我知道)无法通过{children}作为一个属性,我得到一个错误,说未定义“儿童”。我该如何定义孩子?

原始无状态组件:

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;

类组件:

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;

1 个答案:

答案 0 :(得分:0)

您尚未在render方法中定义children变量。道具作为功能组件的第一个参数给出,但在类组件的this.props中可用。

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>
    );
  }
}