我在项目中使用ustated库。
在渲染方法中,我使用set
,如下所示:
render() {
return (
<ApiSubscribe>
{api => (
<button content='CLICK ME' onClick={() => api.setMessage('RENDER CLICK')} />
)}
</ApiSubscribe>
)
}
如何在渲染之外调用api.setMessage
?例如componentDidMount
?
ApiSubscribe是:
export const ApiSubscribe = props => {
// We also leave the subscribe "to" flexible, so you can have full
// control over your subscripton from outside of the module
return <Subscribe to={props.to || [Api]}>{props.children}</Subscribe>;
};
这样?
class Child extends Component {
componentDidMount() {
this.props.api.setMessage('hey')
}
render {...}
]
let Parent = () => (
<ApiSubscribe>
{api => <Child api={api} />}
</ApiSubscribe>
)
您可以创建一个HOC来包装组件,然后以props的形式将容器从HOC组件传递给子组件。