【发布时间】:2019-10-24 09:11:24
【问题描述】:
我目前正在学习 typescript/react,并且正在开发一个小程序来练习我的技能。
我现在卡住了。
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>
//...
);
}
}
我希望用户输入任何值,然后计算新区域,但我不知道如何动态进行。
【问题讨论】:
-
请发布一些代码,而不仅仅是沙箱。
-
很抱歉,我觉得如果我的程序是如何工作的,用视觉表示会更好。
-
别担心,我已经更新了您的问题,并在下面为您提供了答案。另请参阅沙盒 :)
标签: reactjs typescript components