2017-03-26 7 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

が実際にそれがうまく働いている、あなたのコンポーネントが更新されていない参照してください。

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')); 
..あなたは、私がタイプだと思う constructorのあらゆる stateを定義していない持っているという事実に stateに依存
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

関連する問題