簡體   English   中英

反應 在onClick中調用多個事件處理程序將導致“空”或“未定義”

[英]React. Calling multiple event handlers in onClick results in “Null” or “undefined”

我有兩個事件處理程序,一個在組件內(事件稱為“ counter.js”,另一個由props傳遞,其為父項“ container.js”)。

我想傳遞給事件onClick,但是一次只能讓一個工作,而不能同時工作。 我嘗試編寫一個可以同時包含兩個事件並使用該onClick的函數,但隨后出現錯誤。

這兩個事件函數都發現我是否僅使用其中之一,但同時使用它們往往會中斷。 我可以再看看我做錯了什么嗎?

在我的父組件(container.js)中,我將其作為道具傳遞:

    class Container extends Component {
  constructor(props) {
    super(props);

    this.moveCard = this.moveCard.bind(this);
    this.state = {
      id: players.id,
      totalScore: 0,
      countInfo: [],
      evilName: '',
      color: '#6E68C5',
      scoreColor: '#74D8FF',
      fontAwe: 'score-icon',
      incrementcolor: '',
      scoreNameColor: 'white',
      glow: '',
      buttonStyle: 'count-button-start'
    };

    this.incrementCountTotal = this.incrementCountTotal.bind(this);
    this.decrementCountTotal = this.decrementCountTotal.bind(this);
  }

  incrementCountTotal() {
    this.setState({
      totalScore: this.state.totalScore + 1
    });
  }

  decrementCountTotal() {
    this.setState({
      totalScore: this.state.totalScore - 1
    });
  }

  moveCard(dragIndex, hoverIndex) {
    const { cards } = this.state;
    const dragCard = cards[dragIndex];

    this.setState(
      update(this.state, {
        cards: {
          $splice: [[dragIndex, 1], [hoverIndex, 0, dragCard]]
        }
      })
    );
  }

  sortableGroupDecorator = componentBackingInstance => {
    if (componentBackingInstance) {
      let options = {
        group: 'shared'
      };
      Sortable.create(componentBackingInstance, options);
    }
  };

  render() {
    const listPlayers = players.map(player => (
      <Counter
        key={player.id}
        player={player}
        name={player.name}
        sortableGroupDecorator={this.sortableGroupDecorator}
        decrementCountTotal={this.decrementCountTotal}
        incrementCountTotal={this.incrementCountTotal}
      />
    ));
    return (
      <ContainLeft style={{ alignItems: 'center' }}>
        <ProjectTitle>Score Keeper</ProjectTitle>
        <Copy>
          A sortable list of players that with adjustable scores.  Warning, don't go negative!
        </Copy>
        <div>
          <Stats totalScore={this.state.totalScore} players={players} />
          {listPlayers}
        </div>
      </ContainLeft>
    );
  }
}

export default Container;

然后在我的子組件中,我想在onClick區域放置兩個事件,但它們會中斷。 (目前我只有一個事件在onclick,但我想這兩個this.incrementCountincrementCountTotal工作的onClick(該incrementCountTotal從父,在this.incrementCount是子組件

class Counter extends Component {
  constructor(props) {
    super(props);

    this.state = {
      score: 0,
      countInfo: [],
      evilName: '',
      color: '#6E68C5',
      scoreColor: '#74D8FF',
      fontAwe: 'score-icon',
      incrementcolor: '',
      scoreNameColor: 'white',
      glow: '',
      buttonStyle: 'count-button-start'
    };

    this.incrementCount = this.incrementCount.bind(this);
    this.decrementCount = this.decrementCount.bind(this);
  }
  incrementCount() {
    console.log('pressme');
    this.incrementCountTotal;
    this.setState({
      score: this.state.score + 1
    });
    if (this.state.score < 0) {
      this.setState({ color: '#6E68C5' });
      this.setState({ scoreNameColor: 'white' });
      this.setState({ buttonStyle: 'count-button-start' });
      this.setState({ fontAwe: 'fontAwe: score-icon' });
      this.setState({ scoreColor: '#74D8FF' });
      this.setState({ evilName: '' });
    } else if (this.state.score === 9) {
      this.setState({ scoreColor: 'white' });
    } else if (this.state.score === 19) {
      this.setState({ glow: '1px 2px 5px #74D8FF' });
    }
  }

  decrementCount() {
    this.setState({
      score: this.state.score - 1
    });
    if (this.state.score < 0) {
      this.setState({ color: '#381919' });
      this.setState({ scoreNameColor: '#F79D05' });
      this.setState({ buttonStyle: 'count-button-hovering' });
      this.setState({ fontAwe: 'fontAwe: score-icon-switch' });
      this.setState({ scoreColor: '#F79D05' });
      this.setState({ evilName: 'Darth ' });
    } else if (this.state.score === -1) {
      this.setState({ glow: '1px 2px 5px red' });
    } else if (this.state.score === 11) {
      this.setState({ scoreColor: '#74D8FF' });
    } else if (this.state.score === 21) {
      this.setState({ glow: '' });
    }
  }

  render() {
    const {
      name,
      sortableGroupDecorator,
      decrementCountTotal,
      incrementCountTotal
    } = this.props;
    return (
      <div className="group-list" ref={sortableGroupDecorator}>
        <CountCell style={{ background: this.state.color }}>
          <Row style={{ alignItems: 'center' }}>
            <Col>
              <CountButton
                className={this.state.buttonStyle}
                onClick={this.incrementCount}
              >
                <Icon
                  name="icon"
                  className={'fa fa-plus ' + this.state.fontAwe}
                />
              </CountButton>
            </Col>
            <Col>
              <ScoreName style={{ color: this.state.scoreNameColor }}>
                {this.state.evilName + name}
              </ScoreName>
            </Col>
            <Col>
              <Score
                style={{
                  color: this.state.scoreColor,
                  textShadow: this.state.glow
                }}
              >
                {this.state.score}
              </Score>
            </Col>
            <Col>
              <CountButton
                className={this.state.buttonStyle}
                onClick={this.decrementCount}
              >
                <Icon
                  name="icon"
                  className={'fa fa-minus ' + this.state.fontAwe}
                />
              </CountButton>
            </Col>
          </Row>
        </CountCell>
      </div>
    );
  }
}

Counter.propTypes = {
  player: PropTypes.object.isRequired
};

export default Counter;

所以當我添加:

onClick={(this.incrementCount, incrementCountTotal)}incrementCountTotal工作(第二個參數)

如果我用這樣的函數內聯編寫

onClick={event => {
  this.incrementCount;
  incrementCountTotal;
}}

什么都沒有。

如果我寫一個函數來處理這兩個問題,那我就不確定

  onClick(event) {
    incrementCountTotal, incrementCount;
  }

並將onClick={this.onClick}放到:

./src/components/pages/projectpages/dnd2/Counter.js
  Line 97:  'incrementCountTotal' is not defined  no-undef
  Line 97:  'incrementCount' is not defined       no-undef

在子組件中,似乎只需要調用函數(添加括號)即可。 另外,incrementCountTotal是一個prop,因此以這種方式調用它:

  onClick={event => {
    this.incrementCount();
    this.props.incrementCountTotal();
  }
}

暫無
暫無

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

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