未定义'children'-在React类组件中 [英] 'children' is not defined - in React class component

查看:88
本文介绍了未定义'children'-在React类组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

原始无状态组件:

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;

推荐答案

您尚未在render方法中定义 children 变量.这些props作为函数组件的第一个参数给出,但是可以在类组件的 this.props 中获得.

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

这篇关于未定义'children'-在React类组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆