React, Binding input values

I had problems binding the input value, I did it on another component of my application, and it worked fine, but for some reason I can not get it to work with another component. I get only the first letter, not the whole text

This is my component.

class Post extends Component { constructor(props) { super(props); this.state = { post: this.props.data, comment: '' } Post.context = this; } render() { <input type="text" value={this.state.comment} onChange={this.handleChange} placeholder="Write a comment..." /> <button className="button comments" onClick={this.handleClick.bind(null,this.state.post.id)}></button> } handleChange(e) { Post.context.setState({comment: e.target.value}); } } 

I also tried using the example from the React site, but got the same result:

  render() { var valueLink = { value: this.state.comment, requestChange: this.handleChange }; render() { <input type="text" valueLink={valueLink} placeholder="Write a comment..." /> <button className="button comments" onClick={this.handleClick.bind(null,this.state.post.id)}></button> } handleChange(newValue) { Post.context.setState({comment: newValue}); } } 

Does anyone have an idea why this is happening?

+11
source share
1 answer

You must wrap the input and button in the root element (e.g. div)., A component can have only one root element.

You can use .bind as 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 }); } } 

Example

Note: React 16. * contains a new feature - Fragments , which allow you to skip the 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> </> ) } 
+20
source

All Articles