Проблема в том, что вы потребляете свои значения из 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>
//...
);
}
}