2017-08-09 67 views
-1

我正在學習React,並且無法將道具發送到點擊功能。我試圖創建一個簡單的ES6計數器組件,單擊按鈕時該組件會增加。反應:如何發送道具到ES6中的點擊功能?

我點擊功能很簡單:

click() { 
    this.setState({ 
     count: this.state.count + value 
    }) 
} 

我已經設置defaultProps這樣:

Counter.defaultProps = { valueOne: 1 } 

,並創造了我的按鈕,渲染函數中:

<Button className="btn" clickHandler={this.click} text="Click me" value={this.props.valueOne}/> 

但我無法弄清楚是誰讓按鈕將點擊功能「發送」到點擊值上。我剛收到消息value is not defined

任何人都可以在這裏指出我正確的方向嗎?

任何幫助表示讚賞。

我完整的代碼:

 class Counter extends React.Component { 

      constructor(props) { 
       super(props); 
       this.state = { count: 0 }; 
       this.click = this.click.bind(this); 
      } 

      click() { 
       this.setState({ 
        count: this.state.count + value 
       }) 
      } 

      render() { 
       return (
        <div className="container"> 
         <h1>Count {this.state.count}</h1> 
         <Button className="btn blue-btn" clickHandler={this.click} text="Click me" value={this.props.valueOne}/> 
        </div> 
       ) 
      } 

     } 

     Counter.defaultProps = { valueOne: 1 } //Defaults 

     const Button = (props) => { 
      return (
       <button className={props.className} onClick={props.clickHandler} value={props.value}>{props.text}</button> 
      ) 
     } 

     ReactDOM.render(
      <Counter valueOne={1} valueTwo={10} valueThree={100} />, 
      document.getElementById('app') 
     ); 

回答

3

它在event.target.value,只是改變了處理程序:

click(event) { 
    this.setState({ 
     count: this.state.count + event.target.value 
    }) 
} 
1
class Counter extends React.Component { 

      constructor(props) { 
       super(props); 
       this.state = { count: 0, 
           valueOne: 1 
          }; 
       this.click = this.click.bind(this); 
      } 

      click(event) { 
       this.setState({ 
        count: this.state.count + event.target.value 
       }) 
      } 

      render() { 
       return (
        <div className="container"> 
         <h1>Count {this.state.count}</h1> 
         <Button className="btn blue-btn" clickHandler={this.click} text="Click me" value={this.state.valueOne}/> 
        </div> 
       ) 
      } 

     } 

這在本質上你正在嘗試做什麼?

0

您可以通過event.target.value訪問該值。 但我注意到您的代碼中可能存在一個錯誤,因爲this.setState可能會異步執行(如解釋here)。你最好使用接受回調的第二版setState,而不僅僅是一個對象。像這樣:

click(event) { 
     this.setState((prevState) => { 
     return { 
      count: prevState.count + event.target.value 
     } 
     }) 
    }