如何在不指定 props 的情况下将数据传递给孩子



最近我们在 react 中获得了上下文支持。 让我们来看下一个示例:

<Consumer>{value => <Child value={value} />}</Consumer>

如何使组件以相同的方式向其子组件发送"值"? 我的意思是

<MyComponent>{value => ...}</MyComponent>

你让你的组件使用类似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>

也许是高阶组件(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>
)

最新更新