React中props.children能否为无状态组件?Render Props模式报错求助
解决Render Props报错:
this.props.children is not a function 及相关疑问 先聊聊报错原因
你遇到的这个错误,核心问题很直白:你传给ColoredBox的children并不是一个函数,而是一个已经实例化的React元素(也就是<Box />)。在你的ColoredBox组件里,render方法尝试把this.props.children当作函数来调用(this.props.children(this.getState())),但React元素是个对象,根本没法像函数那样执行,所以直接抛出了错误。
关于你的疑问:props.children能不能是无状态组件?
当然可以!无状态组件完全能作为props.children的组成部分,但在Render Props模式下,你不能直接把<Box />丢进去——你得把它包装成一个能接收参数的函数,这样ColoredBox才能把内部的状态数据传递给它。
修正后的代码示例
我把你的代码调整成标准的Render Props写法,你可以对照着看:
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() { // 这里children是函数,调用时传入内部状态 return this.props.children(this.getState()) } } // 关键改动:把Box包装成函数,接收state参数并传递给Box组件 render( <ColoredBox> {(state) => <Box color={state.color} />} </ColoredBox>, document.getElementById('root') // 记得指定挂载节点 );
额外小建议
除了用children作为render prop,你也可以用专门的render属性,这样代码可读性会更高,能避免混淆普通的children和作为函数的children:
// 修改ColoredBox的render方法 render() { return this.props.render(this.getState()) } // 使用时传入render属性 render( <ColoredBox render={(state) => <Box color={state.color} />} />, document.getElementById('root') );
简单来说,Render Props的核心就是父组件通过函数类型的props把数据传递给子组件,不管子组件是无状态组件还是类组件,只要通过函数把数据传进去就行啦。
内容的提问来源于stack exchange,提问作者Madeline Ries
相关产品推荐
相关产品推荐

