2017-01-15 12 views
0

私はes6で新しく、このコードはReact.createClassで動作します。私は、私は別のコンポーネントに渡したい、合計2の機能を持っている私の問題は、私はそのと混乱していている私のコードは次のようである、コンテキスト:別の反応コンポーネントで別の関数を呼び出すにはどうすればよいですか?

class AppOne extends React.Component { 
constructor(props) { 
    super(props); 
this.state = { 
     timers: [ 
     { 
      title: 'Practice squat', 
      project: 'Gym Chores', 
      id: v4(), 
      elapsed: 5456099, 
      runningSince: Date.now() 
     }, 
     { 
      title: 'Bake squash', 
      project: 'Kitchen Chores', 
      id: v4(), 
      elapsed: 1273998, 
      runningSince: null 
     }, 
     ], 
    }; 

    this.func = this.func.bind(this); 
    this.stopTimer = this.stopTimer.bind(this); //<--"Uncaught TypeError: this.stopTimer is 
// not a function" 
} 

func(timerId) { 
     this.stopTimer(timerId); 
} 

stopTimer(timerId) { 
    const now = Date.now(); 

    this.setState({ 
     timers: this.state.timers.map((timer) => { 
      if(timer.id === timerId) { 
       const lastElapsed = now - timer.runningSince; 
       return Object.assign({}, timer, { 
        elapsed: timer.elapsed + lastElapsed, 
        runningSince: null 
       }); 
      } else { 
       return timer; 
      } 
     }), 
    }); 
} 

render() { 
    return (
    <AppTwo handleFuncFromAppOne = {this.func} timers={this.state.timers} /> 
); 
} 
} 

class AppTwo extends React.Component { 
handleFuncFromAppTwo() { 
    this.props.handleFuncFromAppOne(this.props.timers.id) 
} 
render() { 
    return(
    <AppThree handleFuncFromAppThree={this.handleFuncFromAppTwo} /> 
); 
} 
} 

class AppThree extends React.Component { 
render() { 
    return (
    <div 
    className='ui bottom attached red basic button' 
    onClick={this.props.handleFuncFromAppThree} // I want to invoke here 
    > 
    Stop 
    </div> 
); 
} 
} 

あなたは、私はすでには、stopTimerバインド見るアプリケーションでこれをOneとthis.setStateを使用して状態を変更すると、私の問題はApp 3で呼び出すことができないということです。私のエラーは "Uncaught TypeError:this.stopTimerは関数ではありません"です。私はReact.createClassにこの問題があるようには思わない。助けて?

//クラスappTwoは

render() { 
    return(
    <AppThree parentObje={this} /> //pass reference not function 
); 
} 

//class AppThree 

<div 
    className='ui bottom attached red basic button' 
    onClick={this.props.parentObj.handleFuncFromAppThree()} // invoke the //function like this 
    > 

そんなに同じくクラスAppone用することができます:

+0

なぜ「func」からstopTimerを呼び出していますか?また、このエラーが発生するのはいつですか?コンストラクタで、またはfuncを呼び出すとき?また、すでにfuncをラップしている場合は、コンテキストとしてこれを持ちますので、stopTimerをラップする必要はありません。 – Kinnza

+0

@Kinnza、元のコードでコンポーネントのボタンのセットである別のコンポーネントです。このIDはAppTwoの小道具として渡されますAppThreeで呼び出されました.. –

+0

@iamnewbieとkinnza私はあなたの質問に答えたと思います – Codesingh

答えて

1

[OK]を、あなたの問題は、あなたがこのように行うことができますhandleFuncFromAppThree()を定義したクラスの参照を渡していないです。

乾杯:

+0

それは動作します!ありがとうございますが、それを行う別の方法がありますか?同様に、parentObjの小道具を子供から子供に渡す必要はありませんか? –

+0

ええ、これは本当にこれを行う方法ではありません。あなたは親オブジェクトを子オブジェクトに渡すべきではありません....親からメソッドを渡し、コンポーネント内にバインドしないでバインドします。 – Kinnza

関連する問題