javascript - ReactJS: Can not type into input field -
i starting learn react , download , follow tutorials in internet. trying build friend list.
have tree components,
friends_container:
import react 'react'; import addfriend './add_friend.jsx' import showlist './show_list.jsx' class friendscontainer extends react.component { constructor() { this.state = { friends: ['jake lingwall', 'murphy randall', 'merrick christensen'] } } addfriend(friend) { this.setstate({ friends: this.state.friends.concat([friend]) }); } render() { return ( <div> <h3> add friend friendslist </h3> <addfriend addnew={this.addfriend}/> <showlist names={this.state.friends}/> </div> ) } } export default friendscontainer;
add_friend:
import react 'react'; class addfriend extends react.component { constructor() { this.state = {newfriend: ''}; } updatenewfriend(e) { this.setstate({ newfriend: e.target.value }) } handleaddnew() { this.props.addnew(this.state.newfriend); this.setstate({ newfriend: '' }); } render() { return ( <div> <input type="text" value={this.state.newfriend} onchange={this.updatenewfriend}/> <button onclick={this.handleaddnew}>add friend</button> </div> ) } } addfriend.proptypes = { addnew: react.proptypes.func.isrequired }; export default addfriend;
show_list:
import react 'react'; class showlist extends react.component { render() { var listitems = this.props.names.map((f, i) => <li key={i}>{f}</li>); return ( <div> <h3>friends</h3> <ul> {listitems} </ul> </div> ) } } showlist.defaultprops = { names: [] }; export default showlist;
and app.jsx
import react 'react'; import friendscontainer './components/friends_container.jsx'; window.react = react; react.render(<friendscontainer />, document.body);
as can see on code, using es6 , babel transcompiler.
problem, can not type letters input field add new friend friends list. doing wrong?
in context of updatenewfriend
method, this
refers window object , not current component instance. need bind method before passing onchange
event handler. see function::bind
.
you have 2 options:
class addfriend extends react.component { constructor() { // ... this.updatenewfriend = this.updatenewfriend.bind(this); this.handleaddnew = this.handleaddnew.bind(this); } }
or
class addfriend extends react.component { render() { return ( <div> <input type="text" value={this.state.newfriend} onchange={this.updatenewfriend.bind(this)}/> <button onclick={this.handleaddnew.bind(this)}>add friend</button> </div> ) } }
keep in mind function::bind
returns new function, binding in render
creates function every time component rendered, though performance impact negligible.
Comments
Post a Comment