Gab*_*pes 16 javascript data-binding input reactjs
我在绑定输入的值时遇到了一些问题,我已经在我的应用程序的另一个组件上完成了它并且工作正常,但不知怎的,我无法让它在另一个组件上工作.我只收到第一个字母而不是全文
这是我的组成部分
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});
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试使用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});
}
}
Run Code Online (Sandbox Code Playgroud)
有人有想法,为什么会这样?
Ale*_* T. 26
中,必须用input与button在根元素(例如DIV),组分只能有一个根元素.
您可以.bind在我的示例中使用like,并避免使用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 });
}
}
Run Code Online (Sandbox Code Playgroud)
注意: 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>
</>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26925 次 |
| 最近记录: |