简体   繁体   中英

Component is not defined in react?

using login function as component throws an error like this: 'LoginModal' is not defined react/jsx-no-undef I dont know why this happening. Thanks in advance.

export default class Login extends Component {

    state={
        loading: false,
        modalShow: false,
        clicked: false,
        password:''
    }

    LoginModal = () => {
        return <Modal {...this.props} size="lg" aria-labelledby="contained-modal-title-vcenter">
              <Modal.Header closeButton>An otp has been sent to your Email!</Modal.Header>
                <p>something...</p>
                  <Button variant="outline-primary" onClick={this.setState({modalShow:false})} >Change Password</Button>  
            </Modal>
    }
    handleForgetPassword = () => {
        this.setState({modalShow: true})
    }

    handleSubmit = (event) => {
       .....
    }

    render() { 
        return (
            <div>
                <div id="login-wrapper">
                        <p onClick={this.handleForgetPassword} className="forgot-password">forgot password?</p>
                    </div>  
                </div>
                <LoginModal
                    show={this.state.modalShow}
                    onHide={() => this.setState({modalShow:false})}/>
            </div>
        )
    }
}

You should initialize the state in the constructor https://reactjs.org/docs/react-component.html#constructor

  constructor(props) {
    super(props);
    this.state={
        loading: false,
        modalShow: false,
        clicked: false,
        password:''
    }

Also, fix the render method as it's having a missing , or an extra closing tag

render() { 
    return (
        <div>
            <div id="login-wrapper">
                    <p onClick={this.handleForgetPassword} className="forgot-password">forgot password?</p>
             </div>  
            <LoginModal
                show={this.state.modalShow}
                onHide={() => this.setState({modalShow:false})}/>
        </div>
    )
}

You're not referencing LoginModal correctly. You should do something like this instead:

Create a standalone component and then pass props to it

const LoginModal = ({onClick, ...props}) => {
        return <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter">
              <Modal.Header closeButton>An otp has been sent to your Email!</Modal.Header>
                <p>something...</p>
                  <Button variant="outline-primary" onClick={onClick} >Change Password</Button>  
            </Modal>
    }

Try this way

return (
        <div>
             ......
            {this.LoginModal()}
       </div>
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM