因此,我有一个使用'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;
答案 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>
);
}
}