2017-09-05 1 views
1

CounterView.jsインポートモジュールエラーこれは

import React from 'react'; 
const CounterView = <div> 
    <h1>{this.state.counter}</h1> 
    <button onClick={this.handleDecrement}>-</button> 
    <button onClick={this.handleIncrement}>+</button> 
</div>; 
export default CounterView; 

未定義であるCounter.js

import React from 'react'; 
import CounterView from '../ComponentsView/CounterView.js'; 

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

    render() { 
     return (
      < CounterView /> 
     ) 
    } 

} 

富栄私はエラーを得た:

Uncaught TypeError: Cannot read property 'state' of undefined

私を助けてください。 そして、申し訳ありませんBU私は私の質問のために第二の人気があります。私は自分のアプリケーション内の各ファイルに

import React from 'react'; 

を必要としなければならないのはなぜ?彼は最初の呼び出しで1つだけ必要ですか?

答えて

1

コードを適宜変更してください。子コンポーネントから別のコンポーネント状態に到達することはできません。あなたは州の代わりに小道具を使うことができます。

CounterView.js

import React from 'react'; 
class CounterView extends React.Component{ 
    render() { 
     return (
      <div> 
       <h1>{this.props.counter}</h1> 
       <button onClick={this.props.handleDecrement}>-</button> 
       <button onClick={this.props.handleIncrement}>+</button> 
      </div> 
     ); 
    } 
} 
export default CounterView; 

Counter.js

import React from 'react'; 
import CounterView from '../ComponentsView/CounterView.js'; 

class Counter extends React.Component{ 
    constructor(props) { 
     super(props); 
     this.state = { 
      counter: 0, 
     } 
    } 
    handleDecrement() { 
     // do the decrements here 
    } 
    handleIncrement() { 
     // do the increments here 
    } 
    render() { 
     return (
      <CounterView counter={this.state.counter} handleDecrement={this.handleDecrement.bind(this)} handleIncrement={this.handleIncrement.bind(this)} /> 
     ) 
    } 
} 
+0

はそんなにありがとう – zloctb