React 中的 props.children 不能是无状态组件吗?

2024-03-20

我正在尝试在 React 中练习渲染道具模式,但出现了以下错误

this.props.children 不是一个函数

这是我的代码

import React from 'react';
import { render } from 'react-dom';


const Box = ({color}) => (
  <div>
    this is box, with color of {color}
  </div>
);

class ColoredBox extends React.Component {
  state = { color: 'red' }
  getState() {
    return {
      color: this.state.color
    }
  }
  render() {
    return this.props.children(this.getState())
  }
}

render(<ColoredBox><Box /></ColoredBox>, document.getElementById('root'));

https://codesandbox.io/s/8z0xmk9ojl https://codesandbox.io/s/8z0xmk9ojl


正如错误所示, this.props.children 不是一个函数或 React Class(这是一个函数),而是通过调用该函数创建的对象。

您可以使用它来解决问题

render() {
 return React.cloneElement(this.props.children, this.getState())
}

这将使用额外的道具来克隆孩子。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

React 中的 props.children 不能是无状态组件吗? 的相关文章

随机推荐