我正在尝试找到正确的方法来定义一些可以通用方式使用的组件:
<Parent>
<Child value="1">
<Child value="2">
</Parent>
Run Code Online (Sandbox Code Playgroud)
当然,父级和子级组件之间的渲染有一个逻辑,你可以想象<select>并<option>作为这种逻辑的一个例子.
对于问题,这是一个虚拟实现:
var Parent = React.createClass({
doSomething: function(value) {
},
render: function() {
return (<div>{this.props.children}</div>);
}
});
var Child = React.createClass({
onClick: function() {
this.props.doSomething(this.props.value); // doSomething is undefined
},
render: function() {
return (<div onClick={this.onClick}></div>);
}
});
Run Code Online (Sandbox Code Playgroud)
问题是每当你{this.props.children}用来定义包装器组件时,如何将一些属性传递给它的所有子组件?
如何将道具从 Gatsby 布局传递给子级(例如 Header 组件)?
import React from "react";
export default ({ children }) => {
return <div>{children()}</div>;
};
Run Code Online (Sandbox Code Playgroud)
我发现的资源使用以下格式:
{ props.children({ ...props, foo: true }) }
{ this.props.children({...this.props, updateLayoutFunction }) }
Run Code Online (Sandbox Code Playgroud)
但由于没有props,而只有孩子,我无法让它发挥作用。我试过这个,但它也不起作用:
{ children({ foo: true }) }
Run Code Online (Sandbox Code Playgroud)
在所有情况下,我都会收到此错误: TypeError: undefined is not an object (evaluating 'history.listen')
https://github.com/gatsbyjs/gatsby/issues/3412#event-1446894145 https://github.com/gatsbyjs/gatsby/issues/2112
我试图在反应中练习渲染道具,但是我遇到了错误
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)