gpt4 book ai didi

javascript - react ,绑定(bind)输入值

转载 作者:可可西里 更新时间:2023-11-01 01:23:20 24 4
gpt4 key购买 nike

我在绑定(bind)输入值时遇到了一些问题,我已经在我的应用程序的另一个组件上完成了它并且工作正常,但不知何故我无法让它在另一个组件上工作。我只收到第一个字母而不是整个文本

这是我的组件

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});
}
}

有人知道为什么会这样吗?

最佳答案

您必须将inputbutton 包裹在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>
</>
)
}

关于javascript - react ,绑定(bind)输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34037777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com