React,绑定输入值

React, Binding input values

本文关键字:输入 绑定 React      更新时间:2023-09-26

我在绑定输入值时遇到了一些问题,我在应用程序的另一个组件上进行了绑定,效果很好,但不知何故,我无法在另一个部件上进行绑定。我只收到第一封信,没有收到完整的

这是我的组件

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