【问题标题】:React, Binding input values反应,绑定输入值
【发布时间】:2016-03-06 09:37:51
【问题描述】:

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

这是我的组件

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

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

【问题讨论】:

    标签: javascript input data-binding reactjs


    【解决方案1】:

    您必须将inputbutton 包裹在 元素(例如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>
        </>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      • 1970-01-01
      • 2021-04-28
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多