简体   繁体   English

反应 在onClick中调用多个事件处理程序将导致“空”或“未定义”

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

I have two event handlers, one that is within the component (the child called "counter.js" and one passed by props which is the parent "container.js") 我有两个事件处理程序,一个在组件内(事件称为“ counter.js”,另一个由props传递,其为父项“ container.js”)。

I want to pass to events onClick however I can only get one to work at a time, not both. 我想传递给事件onClick,但是一次只能让一个工作,而不能同时工作。 I've tried writing a function that would hold both events and use that onClick but then I get errors. 我尝试编写一个可以同时包含两个事件并使用该onClick的函数,但随后出现错误。

Both events function find if I use just one of them, but using both tends to break. 这两个事件函数都发现我是否仅使用其中之一,但同时使用它们往往会中断。 Can I get a second set of eyes of what I'm doing wrong? 我可以再看看我做错了什么吗?

In my parent component (container.js) I pass this as props: 在我的父组件(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;

Then in my child component I want to put two events on the onClick area but they break. 然后在我的子组件中,我想在onClick区域放置两个事件,但它们会中断。 (currently I only have one event in the onClick but I'd like both this.incrementCount and incrementCountTotal to work onClick (the incrementCountTotal is from the Parent, the this.incrementCount is in the child component (目前我只有一个事件在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;

so when I add: 所以当我添加:

onClick={(this.incrementCount, incrementCountTotal)} only incrementCountTotal works (the second argument) onClick={(this.incrementCount, incrementCountTotal)}incrementCountTotal工作(第二个参数)

If I write it inline with a function like this 如果我用这样的函数内联编写

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

Nothing works. 什么都没有。

If I write a function to handle both it gives me undefined 如果我写一个函数来处理这两个问题,那我就不确定

  onClick(event) {
    incrementCountTotal, incrementCount;
  }

and put onClick={this.onClick} I get: 并将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

In the child component, seems like you just need to call the functions (add parentheses). 在子组件中,似乎只需要调用函数(添加括号)即可。 Also, the incrementCountTotal is a prop, so call it this way: 另外,incrementCountTotal是一个prop,因此以这种方式调用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM