在React中的onClick内调用两个操作

时间:2019-08-27 17:22:41

标签: javascript reactjs onclick

我有一个按钮。我希望一旦用户回答了所有测验问题,该按钮便可以单击。单击按钮后,我想调用computePiePercentages来计算饼图中饼图的大小(以及找出饼图中是否有不适合的饼)。我想显示此饼图computePiePercentages被调用。

但是我在onClick内部的语法上遇到了麻烦。在需要执行两个操作之前,我可以使用以下语法:

<button onClick={this.computePiePercentages}>Click me</button>

但是当我尝试: <button onClick={function(event){ this.computePiePercentages; this._showResults.bind(null, true)}}>Click </button

我得到:Cannot read property 'computePiePercentages' of undefined

class Budget extends React.Component {

  state = {
      data,
      pieChartData: [],
      beyondBudget: {},
      showMessage: bool
  };

  constructor(props) {
    super(props);
    this.state = {
      data,
      pieChartData: [],
      beyondBudget: {},
      showMessage: bool
    };

    // This binding is necessary to make `this` work in the callback
    this.computePiePercentages = this.computePiePercentages.bind(this);

  }

  computePiePercentages(){
    var total = 0
    console.log("hi i am called!!!")
    console.log(this.state.data.selectedQuestions)
    return Object.entries(this.state.data.selectedQuestions).map((element, j)  => {
      console.log(element)
    //return selectedQuestions.map((val, j) => {
      const value = Object.values(element[1])[0]
      total += value

      if(total <= 1600){
        let pieSlice =
             {
               x: name,
               y: value
             };

             this.setState({
                 pieChartData: [...this.state.pieChartData, {x: name, y: value}]
             })
      }
      else {
            const beyondBudget = Object.assign({}, this.state.beyondBudget);

            if (Object.keys(beyondBudget).length == 0) {
                beyondBudget[name] = {};
                beyondBudget[name] = newBudget * -1;
            }
            if (!beyondBudget[name]) {
                beyondBudget[name] = {};
            }
            if (Object.keys(beyondBudget).length > 1) {
                beyondBudget[name] = value;
            }

            this.setState({
                data: {
                    ...this.state.data,
                    selectedQuestions,
                },
                remainingBudget: newBudget,
                beyondBudget: beyondBudget,
            });
        }
    });

}


  handleInputChange = event => {

    let { value, id, name } = event.target;
    value = parseInt(value, 10);

    const selectedQuestions = Object.assign(
      {},
      this.state.data.selectedQuestions
    );



    if (!selectedQuestions[name]) {
      selectedQuestions[name] = {};
    }

    selectedQuestions[name][id] = value;
    console.log(selectedQuestions[name][id])
    this.setState({
                data: {
                    ...this.state.data,
                    selectedQuestions,
                }
    });


  };
  _showResults = (bool) => {
      this.setState({
        showMessage: bool
      });
}
  render() {
      const {
          data,
          remainingBudget,
          pieChartData,
          beyondBudget,
          answeredQuestions,
      } = this.state;
      const questions = data.questions;
      return (
          <div>
              {questions.map((q, i) => (
                  <UL key={i}>
                      <li>
                          <h4>{q.text}</h4>
                      </li>
                      <li>
                          <Options
                              state={this.state}
                              q={q}
                              i={i}
                              handler={this.handleInputChange}
                          />
                      </li>
                  </UL>
              ))}
                <button  onClick={this.computePiePercentages; this._showResults.bind(null, true)}>Click me</button>
                {this.state.showResults &&
                  (<div>
                        <VictoryPie
                            colorScale="blue"
                            data={pieChartData}
                            labels={d => `${d.x}: ${d.y}%`}
                            style={{ parent: { maxWidth: '50%' } }}
                        />

                        {Object.keys(beyondBudget).length > 0 && (
                            <div>
                                <Table>
                                    <tbody>
                                        <tr>
                                            <th>Out of Budget</th>
                                        </tr>
                                        <BrokeBudget
                                            beyondBudget={beyondBudget}
                                        />
                                    </tbody>
                                </Table>
                            </div>
                        )}
                    </div>)
                }
          </div>

      );
  }
  }

2 个答案:

答案 0 :(得分:0)

您可以这样尝试。

<button onClick={(event) => { 
    this.computePiePercentages(); 
    this._showResults.bind(null, true);
}}>Click</button>


在这里,我使用箭头功能一键执行两种不同的方法。

答案 1 :(得分:0)

您可以在操作中使用箭头功能

<button  onClick={(event) => {
   this.computePiePercentages(); 
   this._showResults.bind(null, true);
}}>
Click me
</button>

还是可以在组件中创建新方法 像

onBtnAction = (bool) => {
   this.computePiePercentages(); 
   this._showResults.bind(null, true);
}

然后在OnClick上称为

<button  onClick={this.onBtnAction}>Click me</button>