Event-обработчик не выполняет вычисления - PullRequest
0 голосов
/ 10 июня 2019

В настоящее время я изучаю машинопись / реакцию и работаю над небольшой программой для отработки своих навыков.

Я сейчас застрял.

import React, { Component } from "react";

interface triangleInfo {
  base: number;
  height: number;
  area: number;
  error: string;
}

export default class triangleArea extends React.Component<triangleInfo> {
  constructor(props: triangleInfo) {
    super(props);

    //initializing variables to undefined
    this.handleChange = this.handleChange.bind(this);

    this.state = {
      base: 0,
      height: 0,
      area: undefined,
      error: ""
    };
  }

  //Handling change of input Base and HEIGHT

  handleChange = (input: "base" | "height", value) => {
    this.setState({
      [input]: value
    });
  };

  //getArea function to calculate Area
  getArea = triangleInfo => {
    triangleInfo.preventDefault();

    const { base, height } = this.props;

    if (base > 0 && height > 0) {
      this.setState({
        area: (base * height) / 2
      });
    } else {
      this.setState({
        base: undefined,
        height: undefined,
        area: undefined,
        error: "Please enter the values correctly."
      });
    }
  };

  render() {
    const { base, height } = this.props;

    let resultMarkup;

    //If error is true, prints message to the user
    if (this.props.base < 0 && this.props.height < 0) {
      resultMarkup = (
        <p className="error-m">
          There is an error, please enter positive numbers!
        </p>
      );
    }
    //if erorr is false it will print the current state of the pokemon interface.
    else {
      resultMarkup = (
        //Div with all the information retrieve from the pokemon API

        <div>
          <p>The base of the triangle is: {this.props.base}</p>
          <p>The height of the triangle is: {this.props.height}</p>
          <p>The area of the triangle is: {this.props.area}</p>
        </div>
      );
    }
    return (
      //...
      <div>
        <form onSubmit={this.getArea}>
          <p>Calculate the base of a triangle!</p>
          <input
            type="text"
            id="base"
            placeholder="base"
            value={base}
            onChange={e => this.handleChange("base", e.target.value)}
          />
          <input
            type="text"
            id="height"
            placeholder="height"
            value={height}
            onChange={e => this.handleChange("height", e.target.value)}
          />
          <button type="submit">Get Area</button>

          {resultMarkup}
        </form>
      </div>
      //...
    );
  }
}

Я ожидаю, что пользователь введет любое значение и затем вычислит новую область, однако я не знаю, как это сделать динамически.

1 Ответ

1 голос
/ 10 июня 2019

Проблема в том, что вы потребляете свои значения из props вместо состояния. Когда пользователь заполняет форму, вы обновляете состояние компонента, которое является правильным в вашей настройке handleChange(). Однако в getArea() вы используете ваши значения проп, которые не включают данные, предоставленные пользователем.

https://codesandbox.io/s/somemath-1il3r

import React, { Component } from "react";

interface triangleInfo {
  base: number;
  height: number;
  area: number;
  error: string;
}

interface MyComponentState {
  base: number;
  height: number;
  area: number;
  error: string;
}

export default class triangleArea extends React.Component<
  triangleInfo,
  MyComponentState
> {
  constructor(props: triangleInfo) {
    super(props);

    //initializing variables to undefined
    this.state = {
      base: 0,
      height: 0,
      area: 0,
      error: ""
    };
    this.handleChange = this.handleChange.bind(this);
  }

  //Handling change of input Base and HEIGHT
  handleChange = e => {
    this.setState({ [e.target.name]: e.target.value } as any);
  };

  //getArea function to calculate Area
  getArea = triangleInfo => {
    triangleInfo.preventDefault();

    const { base, height } = this.state;

    if (base > 0 && height > 0) {
      this.setState({
        area: (base * height) / 2,
        error: ""
      });
    } else {
      this.setState({
        base: 0,
        height: 0,
        area: 0,
        error: "Please enter the values correctly."
      });
    }
  };

  render() {
    const { base, height, area, error } = this.state;

    let resultMarkup;

    //If error is true, prints message to the user
    if (this.props.base < 0 && this.props.height < 0) {
      resultMarkup = (
        <p className="error-m">
          There is an error, please enter positive numbers!
        </p>
      );
    }
    //if erorr is false it will print the current state of the pokemon interface.
    else {
      resultMarkup = (
        //Div with all the information retrieve from the pokemon API

        <div>
          <p>The base of the triangle is: {base}</p>
          <p>The height of the triangle is: {height}</p>
          <p>The area of the triangle is: {area}</p>
          <p>{error}</p>
        </div>
      );
    }
    return (
      //...
      <div>
        <form onSubmit={this.getArea}>
          <p>Calculate the base of a triangle!</p>
          <input
            type="text"
            id="base"
            placeholder="base"
            name="base"
            value={base}
            onChange={this.handleChange}
          />
          <input
            type="text"
            id="height"
            placeholder="height"
            value={height}
            name="height"
            onChange={this.handleChange}
          />
          <button type="submit">Get Area</button>

          {resultMarkup}
        </form>
      </div>
      //...
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...