每当我在输入中键入内容时都会调用setState

时间:2019-05-30 03:44:52

标签: reactjs

所以我面临一个问题,就是每当我在输入中写东西时,都会调用handleCommentAdded,它调用setState,重新呈现所有内容。这使得在输入中键入或键入的所有内容都显示为注释,并且当我单击提交以显示为注释时,我想要输入中的内容。我怎样才能解决这个问题?

 class WriteComments extends React.Component {
      constructor(props) {
         super(props);
         this.state = {
         commentAdded:"",
       }
      this.handleButton = this.handleButton.bind(this);
      this.handleCommentAdded = this.handleCommentAdded.bind(this);
  }

  handleCommentAdded(event) {
    this.setState({newComment: event.target.value});
  }

  handleButton() {
    return(
       <div>
       {comment}
       </div>
   )
 }


render() {
  return(
<div>
 <input type="text" value={this.state.commentAdded} onChange=  
   {this.handleCommentAdded}/>

 <div className="button">
    <button
        type="button"
        onClick={e => this.handleButton(e)}
     >
     Write
    </button>
  </div>

   )    }    }

2 个答案:

答案 0 :(得分:0)

错误正在handleCommentAdded上调用onChange
handleButton

中设置状态

class WriteComments extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      commentAdded: ""
    };
    this.inputRef = React.createRef();
    this.handleButton = this.handleButton.bind(this);
  }

  handleButton() {
    this.setState({ commentAdded: this.inputRef.current.value });
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} />

        <div className="button">
          {this.state.commentAdded !== "" ? (
            <div>{this.state.commentAdded}</div>
          ) : (
            <button type="button" onClick={e => this.handleButton(e)}>
              Write
            </button>
          )}
        </div>
      </div>
    );
  }
}



ReactDOM.render(<WriteComments />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />

答案 1 :(得分:0)

我创建了一个演示,可以通过单击按钮获取文本字段值。每次setState调用时,组件都会呈现。希望它能对您有所帮助!

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
{{1}}