如何在ReactJS中基于用户表单输入添加柱状图
Absolutely! Let's get that bar chart up and running for your submitted form data. I'll use Recharts—a lightweight, easy-to-use charting library built specifically for React—to make this straightforward. Here's how to modify your code step by step:
Step 1: Install Recharts
First, add the library to your project:
npm install recharts # or yarn add recharts
Step 2: Update Your Component Code
I've fixed a couple of small issues in your original code (like missing name attributes on inputs, which were breaking your state updates) and added the chart logic:
import React, { useState } from 'react'; // Import required Rechart components import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts'; const Multipleinput = () => { const [userInfo, setUserInfo] = useState({ Name: "", MonthDays: "", Availablefordays: "" }); const [records, SetRecords] = useState([]); const handleInput = (e) => { const name = e.target.name; const value = e.target.value; setUserInfo({ ...userInfo, [name]: value }) } const handleSubmit = (e) => { e.preventDefault(); // Convert numeric values from string to number (critical for charting) const newRecord = { ...userInfo, MonthDays: Number(userInfo.MonthDays), Availablefordays: Number(userInfo.Availablefordays), id: new Date().getTime().toString() } SetRecords([...records, newRecord]); setUserInfo({ Name: "", MonthDays: "", Availablefordays: "" }); } return ( <div style={{ padding: '2rem' }}> <form onSubmit={handleSubmit} style={{ marginBottom: '2rem' }}> <div style={{ marginBottom: '1rem' }}> <label htmlFor="Name">Name</label> {/* Add name attribute to match state keys */} <input type="text" name="Name" value={userInfo.Name} onChange={handleInput} style={{ marginLeft: '0.5rem' }} /> </div> <div style={{ marginBottom: '1rem' }}> <label htmlFor="MonthDays">Month Days</label> <input type="number" name="MonthDays" value={userInfo.MonthDays} onChange={handleInput} style={{ marginLeft: '0.5rem' }} /> </div> <div style={{ marginBottom: '1rem' }}> <label htmlFor="Availablefordays">Available for days</label> <input type="number" name="Availablefordays" value={userInfo.Availablefordays} onChange={handleInput} style={{ marginLeft: '0.5rem' }} /> </div> <button type="submit" >Save User</button> </form> {/* Render chart only when there are records */} {records.length > 0 && ( <BarChart width={600} height={300} data={records} margin={{ top: 20, right: 30, left: 20, bottom: 5 }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="Name" /> {/* Use Name as x-axis labels */} <YAxis /> <Tooltip /> <Legend /> {/* Bar for MonthDays data */} <Bar dataKey="MonthDays" fill="#8884d8" /> {/* Bar for Availablefordays data */} <Bar dataKey="Availablefordays" fill="#82ca9d" /> </BarChart> )} </div> ) } export default Multipleinput;
Key Changes Explained:
- Fixed Input
nameAttributes: YourhandleInputfunction relies one.target.nameto update the state—without these, your form values weren't saving correctly. - Converted Numeric Values: Inputs return string values by default, so we convert
MonthDaysandAvailablefordaysto numbers before saving to records (charts need numeric data). - Conditional Chart Rendering: The chart only shows up once you've submitted at least one record.
- Chart Configuration:
XAxis dataKey="Name"uses the submitted names as labels on the horizontal axis.- Two
Barcomponents map to yourMonthDaysandAvailablefordaysdata, each with a unique color. - Added basic styling (padding, margins) to make the layout cleaner.
How It Works:
Every time you submit the form, a new record is added to the records state array. The Recharts component automatically re-renders with the updated data, showing a side-by-side bar comparison for each user's Month Days and Available Days.
内容的提问来源于stack exchange,提问作者Prateek Singh

