props.children中的响应不能成为无状态组件吗?
问题描述:
我正在尝试在反应中练习渲染道具,但是我得到了
I'm trying to practice render props patter in react but I got error of
this.props.children不是函数
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'));
答
按照render props模式,您需要将孩子作为函数,因此您确实会编写
Following the render props pattern, you need to have your children as a function, so you would indeed write
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>{(color) => <Box color={color}/>}</ColoredBox>, document.getElementById('root'));
也要明确一点,当像<Box/>
但是您可以使用上面的无状态功能组件,例如
However you could use the above stateless functional component like
<ColoredBox>{Box}</ColoredBox>
它会起作用
Demo