Mad*_*ies 5 javascript ecmascript-6 reactjs
我试图在反应中练习渲染道具,但是我遇到了错误
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'));
Run Code Online (Sandbox Code Playgroud)
遵循渲染道具模式,您需要将子级作为函数,因此您确实可以编写
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'));
Run Code Online (Sandbox Code Playgroud)
另外要明确的是,当您像这样渲染无状态功能组件时,它不会被视为与函数相同<Box/>
但是您可以使用上面的无状态功能组件,例如
<ColoredBox>{Box}</ColoredBox>
Run Code Online (Sandbox Code Playgroud)
它会起作用