I'm having some problems with binding the value of an input, I have done it on another component of my app and it worked fine, but somehow I can't get it works on another component. I'm only getting the first letter and 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 to use an example from React website but it 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 someone have idea, why this is happening?
You must wrap
input
andbutton
in root element (for example div)., component can have only one root element.You can use
.bind
like in my example, and avoid usingPost.context = this;
Example
Note: React 16.* contains the new feature -
Fragments
, which allows skipping additional root element.