2017-03-26 35 views
0

我有一個反應代碼,其中有onClicke事件。我想獲得函數的實現(someFunction)。我沒有得到任何錯誤運行這個代碼,一切正常。我想這個問題可以在功能上。該陣營的代碼是onClick事件不會在ReactJS中起作用

class Hello extends Component { 
    constructor() { 
    super(); 
    this.num = { number: 4 }; 
    this.someFunction = this.someFunction.bind(this); 
    } 

    someFunction() { this.setState({ number: this.num.number + 3 }); } 

    render() { 
    const coco = { 
     color: 'blue', 
     background: 'yellow', 
     width: '200px', 
     height: '200px', 
     padding: 'lem' 
    }; 

    return (<div style={coco} onClick={this.someFunction}> 
     <p style={coco} onClick={this.someFunction}> bly blya 
     Hello {this.props.name} </p> 
     <p style={coco} onClick={this.someFunction} > 
     Current count: {this.num.number + 3} 
     </p> 
    </div>) 
    } 
} 

render(<Hello/>, document.getElementById('container')); 

回答

0

實際上它工作得很好,你的組件沒有更新,因爲它不依靠state其實你有沒有定義任何stateconstructor我認爲這是一個類型..

import React , {Component} from 'react' 
import ReactDOM from 'react-dom' 

class Hello extends Component { 
    constructor() { 
    super(); 
    // defining state 
    this.state = { number: 4 }; 
    this.someFunction = this.someFunction.bind(this); 
    } 

    someFunction() { 
    //chnaging state case re-render for component 
    this.setState({number: this.state.number + 3 }); 
    } 

    render() { 
    const coco = { 
     color: 'blue', 
     background: 'yellow', 
     width: '200px', 
     height: '200px', 
     padding: 'lem' 
    }; 

    return (
     <div style={coco} onClick={this.someFunction}> 
     <p style={coco} onClick={this.someFunction}> bly blya 
      Hello {this.props.name} </p> 
     <p style={coco} onClick={this.someFunction} > 
      Current count: {this.state.number + 3 /*need to use state here . */} 
     </p> 
     </div> 
    ) 
    } 
} 

ReactDOM.render(<Hello/>, document.getElementById('container')); 
0

,就應該替換:

Current count: {this.num.number + 3} 

有:

Current count: {this.state.num.number + 3} 
0

無需定義this.num的,你應該在構造函數中定義組件的初始狀態:

this.state = { 
    number: 4, 
}; 

您的函數在點擊回調中被正確調用,但更新狀態的邏輯不起作用,因爲它總是返回相同的狀態。 this.num.number的值始終爲4,因此在撥打setState之後,您的狀態將始終爲7。

您可以使用以前的狀態來計算這樣的新狀態:

this.setState((prevState) => { 
    return { 
     number: prevState.number + 3 
    }; 
}); 

看到這個JSFiddle