React中点击按钮渲染输入框值的实现方法咨询
Hey there! I see what you're trying to do—you want to show the values from your input fields once the Submit button is clicked. Let's adjust your code to make that happen smoothly.
Step 1: Add a Submission Tracking State (Cleaner UX)
First, let's add a simple boolean state to control when we display the submitted values. This way, nothing shows up until the user actually clicks the button, avoiding empty headings initially.
Step 2: Update the submitForm Function
Instead of just logging values to the console, we'll toggle our submission state to trigger the display. Also, let's fix the age state update—number inputs return string values, so we'll convert it to a number to keep the state type consistent.
Step 3: Conditionally Render the Values
We'll use the submission state to only render the h1 and h2 elements after the button is clicked.
Here's the updated code:
import { useState } from 'react'; function Home() { const [name, setName] = useState(''); const [age, setAge] = useState(0); // State to track if the form was submitted const [isSubmitted, setIsSubmitted] = useState(false); const submitForm = () => { console.log(name, age); // Trigger display by setting submission state to true setIsSubmitted(true); } return ( <div> <div> <label htmlFor="name">Name:</label> <input type="text" id="name" // Added matching id for accessibility value={name} onChange={e => setName(e.target.value)} /> </div> <div> <label htmlFor="age">Age:</label> <input type="number" id="age" // Added matching id for accessibility value={age} onChange={e => setAge(Number(e.target.value))} {/* Convert input to number */} /> </div> <button onClick={submitForm}>Submit</button> {/* Only show values after submission */} {isSubmitted && ( <> <h1>{name}</h1> <h2>{age}</h2> </> )} </div> ) } export default Home;
Alternative Simplified Approach
If you don't mind showing empty headings before submission, you can skip the isSubmitted state and just render the name and age states directly:
// Replace the conditional block with this: <h1>{name}</h1> <h2>{age}</h2>
Quick Notes:
- Added
idattributes to inputs to match thehtmlForon labels—this is critical for accessibility (screen readers will associate labels with inputs). - Converting the age input to a number ensures your
agestate stays a numeric type, which is helpful if you need to do calculations later. - The fragment (
<>) lets us group theh1andh2without adding an extra unnecessary DOM element.
内容的提问来源于stack exchange,提问作者 rocco

