React, Binding input values
You must wrap input
and button
in root element (for example div)., component can have only one root element.
You can use .bind
like in my example, and avoid using Post.context = this;
class Post extends React.Component { constructor(props) { super(props); this.state = { post: this.props.data, comment: '' }; } render() { return <div> <input type="text" value={this.state.comment} onChange={ this.handleChange.bind(this) } placeholder="Write a comment..." /> <button className="button comments" onClick={ this.handleClick.bind(this, this.state.post.id)}>Button</button> </div> } handleClick(postId, e) { console.log( postId ); console.log( this.state.comment ); } handleChange(e) { this.setState({ comment: e.target.value }); }}
Note: React 16.* contains the new feature - Fragments
, which allows skipping additional root element.
render() { return ( <> <input type="text" value={this.state.comment} onChange={ this.handleChange.bind(this) } placeholder="Write a comment..." /> <button className="button comments" onClick={ this.handleClick.bind(this, this.state.post.id)} > Button< /button> </> )}