Ответ 1
Вы должны обернуть input
и button
в корневом элементе (например, div)., Компонент может иметь только один корневой элемент.
Вы можете использовать .bind
как в моем примере, и избегать использования 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 });
}
}
Примечание: React 16. * содержит новую функцию - Fragments
, которые позволяют пропустить дополнительный корневой элемент.
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>
</>
)
}