React登录表单报错:'ControlLabel'未从react-bootstrap导出的解决方法
Hey there! That error pops up because ControlLabel was removed from react-bootstrap starting in version 4.x—it's been replaced with a more consistent component. Let's walk through two straightforward ways to fix this:
Option 1: Update your code for modern react-bootstrap versions
This is the recommended approach since newer versions offer better support, bug fixes, and features. Here's what you need to adjust:
- Clean up your imports: Remove
ControlLabelfrom your import list (it no longer exists in v4+). - Replace
ControlLabelwithForm.Label: This is the official replacement component for labeling form inputs. - (Optional but suggested) Swap deprecated
bsSizeprops withsize(sincebsSizewas also phased out in newer versions).
Here's your revised code:
import React, { Component } from "react"; import { Form, Button, FormGroup, FormControl } from "react-bootstrap"; import "./Login.css"; export default class Login extends Component { constructor(props) { super(props); this.state = { email: "", password: "" }; } validateForm() { return this.state.email.length > 0 && this.state.password.length > 0; } handleChange = event => { this.setState({ [event.target.id]: event.target.value }); } handleSubmit = event => { event.preventDefault(); } render() { return ( <div className="Login"> <form onSubmit={this.handleSubmit}> <FormGroup controlId="email" size="lg"> <Form.Label>Email</Form.Label> <FormControl autoFocus type="email" value={this.state.email} onChange={this.handleChange} /> </FormGroup> <FormGroup controlId="password" size="lg"> <Form.Label>Password</Form.Label> <FormControl value={this.state.password} onChange={this.handleChange} type="password" /> </FormGroup> <Button block size="lg" disabled={!this.validateForm()} type="submit" > Login </Button> </form> </div> ); } }
I also removed the unused import Bootstrap from "react-bootstrap"; line—it wasn't serving any purpose in your original code.
Option 2: Downgrade react-bootstrap to version 3.x
If you don't want to modify your code right now, you can install the last version of react-bootstrap that included ControlLabel:
# Using npm npm install react-bootstrap@3 --save # Using yarn yarn add react-bootstrap@3
This will let your existing code work as-is, but keep in mind version 3 is no longer maintained—you'll miss out on future updates and security patches.
内容的提问来源于stack exchange,提问作者riki

