简体   繁体   中英

my event doesn't fire only when its called

in this component I have a button an i have a function for the onClick event, sayHello to test it i just put a console.log to see if it fires when it is clicked, but it only fires when in render the function is called this.sayHello() .

import React, { Component } from "react";
import AsteroidDetails from "./AsteroidDetails";

export default class Asteroids extends Component {
  state = {
    percentageChem: [],
    remainingMass: [],
    asteroidYield: [],
    asteroid: this.props.item,
  };
  sayHello = () => {
    console.log("clicked");
  };
  /*** calculations 
 *   
 remaining m = (mass- all percentages of day )
 m is the remaining mass of the asteroid:


 remaing mpct = (mass - all percentages of day / mass x 100 
    mpct is the remaining percentage mass of the
     asteroid
 */

  /** yield  calculation
   *
   * for mpct >= 0,02
   * yield = (0,04 + ln(mpct) / 100) * m
   *
   * for mpct < 0,02
   * yield = 0
   */

  // function to calculate percentage of chemicals
  percentage = (num, per, t) => {
    return ((num / 100) * per) / t;
  };
  // function to get the sum of all the percentage for one asteroid
  sumPercentage = (percentagearr) => {
    return percentagearr.reduce(function (a, b) {
      return a + b;
    }, 0);
  };

  //function for the remaining mass calculation
  remainingMass = (mass, sum) => {
    return mass - sum;
  };
  //function for the remaining mpct calculation
  remainingMpct = (mass, sum) => {
    return ((mass - sum) / mass) * 100;
  };

  //write yield function
  calcYield = (mass, mptc) => {
    if (mptc >= 0.02) {
      return (0.04 + Math.log(mptc) / 100) * mass;
    } else {
      return 0;
    }
  };

  componentDidMount() {
    console.log(this.props, "props inside Component Did mount"); // props of each asteroid
    const mass = this.props.item.mass;

    let t = 1;
    t = t + Math.round(Math.log10(mass));

    let percentageChem = []; // an empty array for the percentages of chemicals
    Object.entries(this.props.item.chemicals).forEach(([key, value]) => {
      let chem = this.percentage(mass, value, t).toFixed(2); // calculate percentage of chemicals
      percentageChem.push(chem); // push the calulated peprcentage inside percentageChemicals array
    });

    //setting the state for the percentage of chemicals
    this.setState({
      percentageChem: percentageChem,
    });

    console.log(percentageChem, "percentage Chemicals");

    // changing the string array of percentage chemicals to number array
    let numberPercentArray = percentageChem.map((el) => parseFloat(el));

    // calculate the sum of the percentage chemicals array
    let sumOfPercentage = this.sumPercentage(numberPercentArray);

    //total sun if percentage array
    const totalSum = sumOfPercentage.toFixed(2);

    console.log(totalSum, "sum");

    // calculation remaining mass using the total sum and mass.
    const remMass = this.remainingMass(mass, totalSum);
    this.setState({ remainingMass: remMass });
    console.log(remMass, "remaining mass");

    // calculation of remainingmpct using total sum and mass.
    const mpct = this.remainingMpct(mass, totalSum).toFixed(2);
    this.setState({ remainingMpct: mpct });

    console.log(mpct, "remaining mpct");

    //call yield function
    const turnover = this.calcYield(mpct, mass);
    this.setState({ asteroidYield: turnover });
    console.log(turnover, "YIELD?");
  }
  render() {
    return (
      <div className="as">
        <AsteroidDetails
          chemPerDay={this.state.percentageChem}
          asteroid={this.state.asteroid}
          remainingMassPerday={this.state.remainingMass}
          asteroidYieldPerDay={this.state.asteroidYield}
        />

        <button onClick={this.sayHello}>Click</button>
      </div>
    );
  }
}

Thats because are invoking function on each render. You need to create closure and put your function in it.

Try this:

<button onClick={()=> {this.sayHello()}}>Click</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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