簡體   English   中英

如何在另一個React組件上調用另一個函數?

[英]How do I invoke another function on another react component?

我是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>
  );
 }
}

您看到我已經在應用程序One上綁定了stopTimer,並且它使用this.setState更改狀態,我的問題是我無法在應用程序3上調用它。 我的錯誤是“未捕獲的TypeError:this.stopTimer不是函數”。 我似乎在React.createClass上沒有這個問題。 救命?

好的,您的問題是您沒有傳遞定義了handleFuncFromAppThree()的類的引用,您可以這樣做:

//類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類進行類似的處理。

干杯:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM