I began to study the reactor and faced a situation that I don’t understand in principle, but I really want to understand: how is the "listening" of global variables organized in the react, which are available to all classes within a single application or script?

I will give an example in pseudocode:

var a = false; var globalVariable = function(e) { a = e.target.value; } var ExampleClassA = React.createClass({ getInitialState: functuion () { return { globalAccess: false } } render: function() { return ( <div> <input type='checkbox' onChange={globalVariable.bind(this)}/> </div> ) } }) var ExampleClassB = React.createClass({ render: function() { return ( <span>{то, что поможет как-нибудь получить значение a}</span> ) } }) 

Of course, there may be a lot of mistakes, but the picture is clear in principle.

  • In the code there is nothing from the formulated question. And still it would be necessary to distinguish values ​​and functions. - Qwertiy
  • @Qwertiy, I can’t understand how to do it that I can’t articulate normally. Changed a little, but I do not think that the general concept of "wrongness" has changed. Sorry, that alas so: ( - lamartire
  • Make a workable snippet . - Qwertiy

1 answer 1

In order for ExampleClassB detect a change in the variable a , you need to embed both components into a common parent component, where the variable a will already be a member of the state object of the parent component, into the ExampleClassB component pass through properties. The parent method for changing a variable must also be passed through the property to the ExampleClassA component.

Sample code:

 var ExampleClassA = React.createClass({ render: function() { return ( <div> <input type='checkbox' onChange={this.props.onChange}/> </div> ); } }); var ExampleClassB = React.createClass({ render: function() { return ( <span>{this.props.a? "true" : "false"}</span> ); } }); var ParentClass = React.createClass({ getInitialState() { return { a: false }; }, changeVariable(e) { this.setState({a: e.target.checked}); }, render() { return( <div> <ExampleClassA onChange={this.changeVariable} /> <ExampleClassB a={this.state.a} /> </div> ); } }); 

Performance can be checked here: https://jsfiddle.net/szepej8o/

  • Yes, I have already figured out this question a long time ago, thank you :) - lamartire