简体   繁体   中英

Access React component's state inside a non React file

I have a backbone file and inside it, I render a React component (Timer) by using React.renderComponent. However, in the react component, I have a state call counter. I would like to get the state of this component from the backbone file. Although I passed a props.model into Timer, I can modify this props inside Timer for sure, but this will make data in props.model persist, which I don't want to do.

Since Timer is not a child of a React component, I am not able to use refs to access Timer.stat. So is there a way to get Timer's state in its parent?

Thanks very much!

State is not intended to be accessible on read or pull queries from outside the component. State is private to the component itself and its children.

If you need access to the variable, you have a couple of options:

  • Make the react component send out some change event everytime state changes, to inform others about new state
  • Keep track of it outside the react component and pass it as a prop to the component itself.
  • (dirty solution: do not try this at home) : let the react component put the specific state variable inside a data-attribute of the HTML code to be rendered, eg <div data-foo={this.state.foo}> and read that property from the DOM afterwards. In most cases, react always re-renders if state changes, so your property is always in sync with state.

Really only use the last option as an escape if all else fails. Because it goes against design principles of react.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM