-1

All:

I am pretty new to React, when I try to make a very simple component like a inputbox with a label, which the label can change according to the input of input box.

class App extends React.Component {
    constructor() {
        super();
        this.name = "World";
    }
    changeName(e){
        var nameinput = this.refs.nameinput;
        this.name = nameinput.value;
    }
    render(){
        return  (
            <div>
                <input ref="nameinput" onChange={this.changeName} />
                Hello, {this.name}!
            </div>
            );
    }
}

Currently the problem is in changeName() function, there is no reference to App( when I print out this, it is undefined) I wonder how can I get the reference to that inputbox with something like refs.nameinput.value

Thanks

Kuan
  • 11,149
  • 23
  • 93
  • 201

2 Answers2

2

You need to bind your event handler:

<input ref="nameinput" onChange={this.changeName.bind(this)}/>

See this question for more details on this:

How to access the correct `this` context inside a callback?

Community
  • 1
  • 1
SimpleJ
  • 13,812
  • 13
  • 53
  • 93
  • thanks, now it works, but I wonder why the render function does not get called, does that mean I have to manually call this.setState() everytime I run a event ahndler? I am kinda wonder if my state data structure is very deep, how do I write it in setState() ( like this.AA.BB.CC.DD.XXX.name)? – Kuan Mar 31 '16 at 23:19
  • You will need to call `setState`. You will need to move `name` into the `state` property of your component. `setState` shallowly merges with the existing state, but it won't merge deeply nested objects (you can however manually merge your nested data with changes using `Object.assign`). I'd recommend trying to flatten your data and look into immutability. – SimpleJ Mar 31 '16 at 23:39
  • Thanks, good idea, I will read that – Kuan Mar 31 '16 at 23:40
1

Or you can bind it in your constructor

constructor() {
        super();
        this.name = "World";
        this.changeName = this.changeName.bind(this);
    }
tomRedox
  • 28,092
  • 24
  • 117
  • 154
  • now it works, but I wonder why the render function does not get called, does that mean I have to manually call this.setState() everytime I run a event ahndler? I am kinda wonder if my state data structure is very deep, how do I write it in setState()? – Kuan Mar 31 '16 at 22:29