React+TypeScript三角形面积组件报错:Cannot find name 'base'.ts(2304)
Hey there, let's break down what's going wrong with your component and fix it step by step! I've identified a few key issues that are causing the error and preventing proper value handling:
Key Problems & Fixes
1. Undefined base/height in Render
You're trying to reference base and height directly in your input elements, but these variables don't exist in the render scope. They're stored in your component's state, so you need to access them via this.state.base and this.state.height.
2. Fetching Values from props Instead of state
In your getArea function, you're destructuring base and height from this.props, but those values are being tracked in the component's internal state. You should pull them from this.state instead.
3. Type & Input Parsing Issues
- The
handleChangefunction'svalueparameter lacks a type annotation. - Input values from text fields are strings, so you need to convert them to numbers before storing them in state (otherwise, your area calculation will concatenate strings instead of multiplying numbers).
- You should also handle cases where users enter non-numeric values to avoid errors.
4. Incorrect Component Generic Typing
Your component is using React.Component<triangleInfo> which treats triangleInfo as the props type, but this component doesn't accept external props. The correct syntax is React.Component<{}, triangleInfo> where the first empty object represents props, and the second is your state type.
5. State Initialization vs. Interface Mismatch
Your triangleInfo interface defines area as a number, but you initialized it as undefined. Update the interface to allow area to be number | undefined to match the state.
Corrected Full Code
import React, { Component } from "react"; // Updated interface to allow area/error to be undefined interface TriangleInfo { base: number | undefined; height: number | undefined; area: number | undefined; error: string; } // Fixed generic typing: empty props object + state type export default class TriangleArea extends React.Component<{}, TriangleInfo> { constructor(props: {}) { super(props); this.state = { base: undefined, height: undefined, area: undefined, error: "" }; } // Updated handleChange with proper typing and number conversion handleChange = (input: "base" | "height", value: string) => { // Convert input to number, or set to undefined if not a valid number const numericValue = !isNaN(Number(value)) && value !== "" ? Number(value) : undefined; this.setState({ [input]: numericValue }); }; // Fixed getArea to use state values and proper typing getArea = (e: React.FormEvent) => { e.preventDefault(); const { base, height } = this.state; if (base && height && base > 0 && height > 0) { this.setState({ area: (base * height) / 2, error: "" }); } else { this.setState({ area: undefined, error: "Please enter valid positive numbers for base and height." }); } }; render() { const { base, height, area, error } = this.state; // Destructure state for cleaner code return ( <div> <form onSubmit={this.getArea}> <p>Calculate the area of a triangle!</p> {/* Access values from state, fixed typo in heading */} <input type="text" id="base" placeholder="base" value={base || ""} // Handle undefined state to avoid input errors 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> </form> {/* Display area or error message */} {area && <p>Triangle Area: {area}</p>} {error && <p style={{ color: "red" }}>{error}</p>} </div> ); } }
Additional Notes
- I renamed
triangleAreatoTriangleArea(PascalCase is standard for React component names). - Added destructuring of state in the render method for cleaner code.
- Added handling for undefined state values in inputs (using
value={base || ""}) to prevent React warnings about uncontrolled inputs. - Improved error message clarity and added display for the calculated area/error.
内容的提问来源于stack exchange,提问作者Daniel Isaac Chavez

