You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React入门开发:创建含关键词、城市输入与日期选择的表单

Hey there! Let's get your React form up and running step by step. Since you're just starting out, I'll keep things clear and straightforward so you can follow along easily.

First, Fix Up Your index.html

Your current HTML is missing the necessary React and Babel dependencies to run JSX in the browser. Let's update it with CDN links and some basic styling to make the form look decent:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Application</title>
    <!-- Import React and ReactDOM libraries -->
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <!-- Import Babel to compile JSX into browser-readable JavaScript -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <!-- Simple styling for the form -->
    <style>
        .form-container {
            max-width: 400px;
            margin: 2rem auto;
            padding: 1.5rem;
            border: 1px solid #eee;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 1rem;
        }
        label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
        }
        input, select {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
        }
        button {
            width: 100%;
            padding: 0.75rem;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 1rem;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div id="root"></div>
    <!-- Link your index.js file (marked as text/babel so Babel processes it) -->
    <script type="text/babel" src="index.js"></script>
</body>
</html>

Next, Complete Your index.js Code

We'll create a functional React component for your form, using React's useState hook to manage form state, and handle input changes and form submission:

// No need for imports if using CDN (React and ReactDOM are global)
// If you're using Create React App, keep these imports:
// import React from 'react';
// import ReactDOM from 'react-dom/client';

function SearchForm() {
    // Initialize form state with empty values for each field
    const [formData, setFormData] = React.useState({
        keywords: '',
        city: '',
        date: ''
    });

    // Reusable function to handle input changes for all fields
    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData(prevState => ({
            ...prevState, // Keep existing state values
            [name]: value // Update the specific field that changed
        }));
    };

    // Handle form submission
    const handleSubmit = (e) => {
        e.preventDefault(); // Stop the browser's default form reload behavior
        // Here's where you'd add your submission logic (e.g., send data to an API)
        console.log('Submitted Form Data:', formData);
        alert(`Search Details:\nKeywords: ${formData.keywords}\nCity: ${formData.city}\nDate: ${formData.date}`);
        // Optional: Reset the form after submission
        setFormData({ keywords: '', city: '', date: '' });
    };

    return (
        <div className="form-container">
            <h2>Search Form</h2>
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="keywords">Keywords:</label>
                    <input
                        type="text"
                        id="keywords"
                        name="keywords"
                        value={formData.keywords}
                        onChange={handleInputChange}
                        placeholder="Enter search keywords"
                        required // Makes this field mandatory
                    />
                </div>
                <div className="form-group">
                    <label htmlFor="city">City:</label>
                    <input
                        type="text"
                        id="city"
                        name="city"
                        value={formData.city}
                        onChange={handleInputChange}
                        placeholder="Enter city name"
                        required
                    />
                </div>
                <div className="form-group">
                    <label htmlFor="date">Date:</label>
                    <select
                        id="date"
                        name="date"
                        value={formData.date}
                        onChange={handleInputChange}
                        required
                    >
                        <option value="">Select a date</option>
                        <option value="2024-05-01">2024-05-01</option>
                        <option value="2024-05-02">2024-05-02</option>
                        <option value="2024-05-03">2024-05-03</option>
                        <!-- Add more date options as needed -->
                    </select>
                </div>
                <button type="submit">Submit Search</button>
            </form>
        </div>
    );
}

// Render the component to the root div in your HTML
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<SearchForm />);

Key Concepts Explained

  • Controlled Components: Every input/select element is linked to the formData state via value and onChange, ensuring the UI always reflects the current state.
  • useState Hook: Manages the form's state in a single object, making it easy to update and access all fields.
  • Reusable Handler: The handleInputChange function works for all fields by using the name attribute to match the state key, so you don't need separate functions for each input.

If You're Using Create React App

If you started with create-react-app, you don't need the CDN links in index.html. Just keep the imports at the top of index.js and replace the root render code with:

root.render(
  <React.StrictMode>
    <SearchForm />
  </React.StrictMode>
);

That's it! Open your index.html in a browser, and you'll have a fully functional React form. Test it out by entering values and submitting—you'll see your data logged to the console and an alert with the details.

内容的提问来源于stack exchange,提问作者Heidel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:17:37