gpt4 book ai didi

javascript - react 中的 props.children 不能是无状态组件?

转载 作者:数据小太阳 更新时间:2023-10-29 06:14:19 26 4
gpt4 key购买 nike

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

this.props.children is not a function

这是我的代码

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

最佳答案

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

你可以用它来解决问题

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

这将带 child ,使用额外的 Prop 克隆它。

关于javascript - react 中的 props.children 不能是无状态组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49891935/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com