我正在尝试通过ref
访问我的电子邮件和密码字段,但是无论如何我都得到一个未定义的值。
这是我的代码:
import React, { Component } from 'react'
import { Button,
Modal,
ModalHeader,
ModalBody,
ModalFooter,
Form,
FormGroup,
Input
} from 'reactstrap';
class LoginModal extends Component {
constructor(props) {
super(props);
this.email = React.createRef();
this.password = React.createRef();
};
login (e) {
e.preventDefault();
const email = this.email
const password = this.password
console.log(email, password)
}
render () {
return (
<Modal>
<ModalHeader>Connexion</ModalHeader>
<ModalBody>
<Form onSubmit={this.login}>
<FormGroup>
<Input type="email" name="email" ref={this.email} placeholder="Email" />
</FormGroup>
<FormGroup>
<Input type="password" name="password" ref={this.password} placeholder="Mot de passe" />
</FormGroup>
<Button type="submit" color="primary">CONNEXION</Button>
</Form>
</ModalBody>
<ModalFooter>
Footer
</ModalFooter>
</Modal>
)
}
}
export default LoginModal
我正在使用反应16.5.2。
我是根据文档here
完成的答案 0 :(得分:1)
您需要将方法绑定到构造函数中
this.login = this.login.bind(this)
还要获取参考值,您将使用current
login (e) {
e.preventDefault();
const email = this.email
const password = this.password
console.log(email.current.value, password.current.value)
}