React,绑定输入值
React, Binding input values
我在绑定输入值时遇到了一些问题,我在应用程序的另一个组件上进行了绑定,效果很好,但不知何故,我无法在另一个部件上进行绑定。我只收到第一封信,没有收到完整的
这是我的组件
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});
}
}
我也尝试使用React网站上的一个例子,但得到了相同的结果:
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});
}
}
有人知道为什么会发生这种事吗?
必须将input
和button
包装在root元素中(例如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 });
}
}
Example
注意: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>
</>
)
}
相关文章:
- 绑定Range输入以修改样式
- Knockout输入绑定不起作用
- javascript绑定另一个select2输入字段rails的select2 inputonchange事件的数据
- AngularJS-将数组值绑定到输入ngModel
- 指令中选择输入的双向绑定不起作用
- 将隐藏的输入绑定到角度中的模型
- 将文本输入绑定到可观察数组的值
- 材料设计余烬输入绑定不工作
- 如何将输入绑定到vue.js模型
- 输入绑定
- 使用knockout将图像源与文件输入绑定
- React + Flux——将输入绑定到单个“模型”的嵌套组件
- 如何将两个输入绑定到一个函数
- 在angular中将输入绑定到对象数组
- dom绑定中的纸张输入绑定
- 角度输入绑定两个字段
- 将文本输入绑定到指令属性
- HTML-将文本输入绑定到标签
- 如何使用文本输入绑定触发函数
- 如何清除输入绑定到谷歌位置自动完成