W
W
weredy2016-11-07 19:04:19
JavaScript
weredy, 2016-11-07 19:04:19

How can a method be accessible inside an object via this, but not be accessible from outside by name?

React has a setState() method that can be used inside the object you pass in to instantiate it:

var MyComponent = React.createClass({
            getInitialState: function() {
                return {
                    myState: 1
                };
            },

            myMethod: function() {
              this.setState({
                    myState: 1
                })
            },

            render: function() {
                return (
                    <h1>Тест</h1>
                );
            }
        });

But when calling MyComponent.setState from outside: Uncaught TypeError: MyComponent.setState is not a function(...)
Unfortunately, my level does not allow me to understand what is happening in the React code, I'm just trying to understand the JS itself, how I organize such things.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Aves, 2016-11-07
@weredy

MyComponent is a constructor function, setState on the prototype. You need to create a component instance.

var instance = ReactDOM.render(<MyComponent />. document.body);
instance.setState({myState: 1});

(new MyComponent()).setState() is also supposed to work.

S
Sergey Semenko, 2016-11-07
@abler98

https://learn.javascript.ru/bind

A
Alex Zeit, 2016-11-07
@idtimeless

I don't quite understand - why do you need setState outside?
if you just want to pass parameters - pass them in this form

ReactDOM.render(<MyComponent myState='1' /> , document.body);
.... 
render: function() {
                return (
                    <h1>Тест { this.props.myState}</h1>
                );
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question