簡體   English   中英

如何在React.js中使按鈕交互?

[英]How to make the button interactive in React.js?

請指出我的錯誤。

我想寫一個交互式按鈕,顯示它的點擊次數。 每次下一次單擊時,按鈕上的數字必須增加1。 初始編號為0,因此,例如,在5次單擊后,它變為5.沒有交互式元素,代碼將正常呈現。

這是我的代碼:

class Button extends React.Component{
  constructor(props){
    super(props);
    this.state = {counter: 0};
  };

  handleClick(){
    this.setState(
      prevState => ({counter: prevState.counter + 1})
    );
  }

  render(){
    return (
      <button onClick={this.handleClick}>{this.state.counter}</button>
    );
  }
}

這是我得到的錯誤:

TypeError: Cannot read property 'setState' of undefined
handleClick
src/index.js:30:6
  27 | 
  28 |   render(){
  29 |     return (
> 30 |       <button onClick={this.handleClick}>{this.state.counter}</button>
     |      ^  31 |     );
  32 |   }
  33 | }
View compiled
▶ 20 stack frames were collapsed.

先感謝您!

在你的榜樣, this在你的handleClick()函數是指從您的點擊觸發事件的范圍。 為了解決這個問題,您必須將函數范圍綁定到元素。

this.handleClick = this.handleClick.bind(this)添加到您的構造函數中,它應該可以正常工作。

https://reactjs.org/docs/handling-events.html

您可以更高級一點,並使用ECMAScript 6箭頭函數語法,這將避免這種問題,也避免使用.bind(this)

如果你聲明handleClickhandleClick = () => {} ,你將不需要在你的構造函數this.handleClick.bind(this) 一切都將正常工作,當你使用this ,這將是類的this ,而不是函數的this

這是使用較新版本的javascript,強烈建議不要使用.bind(this) ,這可能會導致一些問題。

只需聲明handleClick就像這樣,它將工作而無需使用.bind(this)

  handleClick = () => {
    this.setState(
      prevState => ({counter: prevState.counter + 1})
    );
  }

您必須綁定單擊處理程序:

...
  constructor(props){
    super(props);
    this.state = {counter: 0};
    this.handleClick.bind(this) // <----- here
  }
...

我想你有兩個選擇:

  1. 將bind添加到構造函數中。 this.handleClick.bind(this) ,這將保證您的this實際上指的是按鈕對象。
  2. 使用更新的格式,我更喜歡。

     handleClick = () => { this.setState( prevState => ({counter: prevState.counter + 1}) ); } 

關於很多React主題的更多有用文檔: https//reactjs.org/docs/react-component.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM