How to use react unstated outside of render method?

 ̄綄美尐妖づ 提交于 2019-12-21 13:08:39

问题


I am using ustated library in my project.

In render method, I am using set like this:

render() {
    return (
            <ApiSubscribe>
                {api => (
                    <button content='CLICK ME' onClick={() => api.setMessage('RENDER CLICK')} />
                )}
            </ApiSubscribe>
    )
}

How can I call api.setMessage OUTSIDE of render? For example in componentDidMount ?

ApiSubscribe is:

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>;
};

回答1:


Like this?

class Child extends Component {
  componentDidMount() {
    this.props.api.setMessage('hey')
  }
  render {...}
]

let Parent = () => (
  <ApiSubscribe>
    {api => <Child api={api} />}
  </ApiSubscribe>
)



回答2:


You can create a HOC to wrap your component, then pass the container from the HOC component to the child component in the form of props.



来源:https://stackoverflow.com/questions/51573978/how-to-use-react-unstated-outside-of-render-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!