反应,绑定输入值 [英] React, Binding input values

查看:119
本文介绍了反应,绑定输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having some problems with binding the value of an input, I have done it on another component of my app and it worked fine, but somehow I can't get it works on another component. I'm only getting the first letter and not the whole text

这是我的组件

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网站的一个例子,它得到相同的结果:

I also tried to use an example from React website but it got the same result:

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

有人有想法,为什么会发生这种情况? / p>

Does someone have idea, why this is happening?

推荐答案

您必须包装输入 / code>在元素(例如div)中,组件只能有一个根元素。

You must wrap input and button in root element (for example div)., component can have only one root element.

您可以使用 .bind 像我的例子一样,避免使用 Post.context = this;

You can use .bind like in my example, and avoid using 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 });
  }
}

示例

这篇关于反应,绑定输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆