最近我们得到了Context支持。 让我们看下一个例子:
<Consumer>{value => <Child value={value} />}</Consumer>
如何制作发送&#34;值&#34;的组件?它的孩子一样吗? 我的意思是
<MyComponent>{value => ...}</MyComponent>
答案 0 :(得分:3)
您使组件使用render props callback pattern
之类的
class MyComponent extends React.Component {
state = {
value: 'abc'
}
render() {
return React.Children.only(this.props.children)(this.state.value)
}
}
然后你可以像
一样使用它<MyComponent>{value => ...}</MyComponent>
答案 1 :(得分:2)
也许是higher order component (HOC)?
function withContext(Component) {
return WithContext = (props) => (
<Consumer>
{
value => <Component {...props} value={value} />
}
</Consumer>
)
}
let MyComponent = ({ value }) => (
<div>
{value} // if value is something that can be rendered
</div>
)
MyComponent = withContext(MyComponent);
const MyComponent = (props) => (
<Consumer>
{value => props.children(value)}
</Consumer>
)
const example = (
<MyComponent>
{value => <div>{value}</div>} // children prop has to be function now
</MyComponent>
)