Как передать функцию как свойство компоненту React? - PullRequest
1 голос
/ 02 ноября 2019

В попытке выяснить проблему, которую я объясняю в своем (без ответа) вопросе "Как мне обновить значение ячейкиact-bootstrap-table2 после того, как оно отредактировано, чтобы компонент кнопки в другом столбце имел его?", я попытался передать функцию, которая возвращает значение ячейки, в компонент кнопки:

class NominationQueueBootstrapTable extends Component {

...

  getInitialBid = (row) => {
    console.log('getInitialBid');
    return this.state.data.find(r => r.rank === row.rank).initialBid;
  }

  render() {
    const { auctionId } = this.props;
    const { teamId } = this.props;

    function buttonFormatter(cell, row) {
      return (
        <NominateButton
          row={ row }
          auctionId={ auctionId }
          teamId={ teamId }
          getInitialBid={ this.getInitialBid }
        />
      );
    }

...

Мой NominateButton компонент возвращает другой компонент-оболочку кнопки, который вызывает мутатор:

class NominateButton extends Component {
  render() {
    const { row } = this.props;
    const { auctionId } = this.props;
    const { teamId } = this.props;
    const playerId = parseInt(this.props.row.player.id, 10);

    return (
      <Query
        query={TEAM_NOMINATIONS_OPEN_QUERY}
        variables={{ team_id: teamId }}>
        {({ data, loading, error, subscribeToMore }) => {
          if (loading) return <Loading />;
          if (error) return <Error error={error} />;
          return (
            <NominateButtonMutator
              auctionId={ auctionId }
              teamId={ teamId }
              playerId={ playerId }
              row={ row }
              nominationsOpen={ data.team.nominationsOpen }
              subscribeToNominationsOpenChanges={ subscribeToMore }
              getInitialBid={ this.props.getInitialBid }
            />
          );
        }}
      </Query>
    );
  }
}

И поскольку мне нужно вызывать мутатор при нажатии кнопки, моя функция onClick сначала вызывает функцию getInitialBid, переданную как свойство, а затем вызывает мутатор:

class NominateButtonMutator extends Component {

...

  handleButtonPressed = (submitBid) => {
    this.setState({bidAmount: this.props.getInitialBid(this.props.row)});
    submitBid();
  };

  render() {
    const { auctionId } = this.props;
    const { teamId } = this.props;
    const { playerId } = this.props;
    const { nominationsOpen } = this.props;

    return (
      <Mutation
        mutation={SUBMIT_BID_MUTATION}
        variables={{
          auction_id: auctionId,
          team_id: teamId,
          player_id: playerId,
          bid_amount: this.state.bidAmount
        }}
      >
        {(submitBid, { loading, error }) => (
          <div>
            <Error error={error} />
            <Button
              disabled={ loading || !nominationsOpen }
              onClick={() => this.handleButtonPressed(submitBid) }
              variant="outline-success">
              Nominate
            </Button>
          </div>
        )}
      </Mutation>
    );
  }
}

(Код onClick= был обновлен из комментария azium .)

Когда я запускаю это, я получаю:

"Ошибка типа: this.props. getInitialBid не является функцией "

enter image description here

Это работоспособная стратегия? Почему this.props.getInitialBid не является функцией?

1 Ответ

1 голос
/ 02 ноября 2019

Вы используете старый синтаксис function, поэтому this не связан правильно.

измените:

function buttonFormatter(cell, row) {
  return (
    <NominateButton
      row={ row }
      auctionId={ auctionId }
      teamId={ teamId }
      // scoped to your local function not your class
      getInitialBid={ this.getInitialBid } 
    />
  );
}

на

const buttonFormatter = (cell, row) => {
  return (
    <NominateButton
      row={ row }
      auctionId={ auctionId }
      teamId={ teamId }
      // this is scoped "lexically" aka to your class
      getInitialBid={ this.getInitialBid }
    />
  );
}
...