Reputation: 313
Tried to get input's value when user click search but failed.
var Login = React.createClass({
getInitialState: function () {
return {name: ''};
},
handleSearch(){
alert(this.state.name); // doesn't work?
},
handleChange(e){
this.setState({name: e.target.value});
},
render() {
return <div>
<input type="text" placeholder="name" onChange="{this.handleChange}" value=""/><button onClick={this.handleSearch}>Search</button>
</div>;
}
})
is there any more straight forward to get the value of input?
Upvotes: 1
Views: 63
Reputation: 1074555
The principal issue is that you have quotes around your onChange
:
onChange="{this.handleChange}"
it shouldn't have them, that's setting it to a string value. Just:
onChange={this.handleChange}
(as you did with onClick
on the button).
You'll also need to set value
to this.state.name
:
var Login = React.createClass({
getInitialState: function () {
return {name: ''};
},
handleSearch(){
console.log("name is", this.state.name);
},
handleChange(e){
this.setState({name: e.target.value});
},
render() {
return <div>
<input type="text" placeholder="name" onChange={this.handleChange} value={this.state.name} /><button onClick={this.handleSearch}>Search</button>
</div>;
}
});
ReactDOM.render(
<Login />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Upvotes: 4