我有一个React应用程序(带有React Segment UI),到目前为止工作正常。我有一个登录表单,作为任何登录表单,我允许它由密码管理器或浏览器自动填充。我想要做的是抓住预填表格中的值,主要是检查它们是否已经填满。
我该怎么做?
目前这是我的组件的样子:
export default class SignIn extends React.PureComponent {
handleSubmit (evt) {
// handle submit
}
isSignInDisabled () {
// Would like to check here is the email and password
// have been prefilled since with this method it won't work
// in this case.
return (
!this.props.email.length ||
!this.props.password.length
)
}
render () {
const { email, password } = this.props
return (
<Form onSubmit={evt => {
this.handleSubmit(evt)
}}>
<Form.Field>
<Form.Input
type='email'
label='Email'
value={email}
onChange={evt => setEmail(evt.target.value)}
/>
</Form.Field>
<Form.Field>
<Form.Input
type='password'
label='Password'
value={password}
onChange={evt => setPassword(evt.target.value)}
/>
</Form.Field>,
<Form.Field>
<Button type='submit' disabled={this.isSignInDisabled()}>Sign In</Button>
</Form.Field>
</Form>
)
}
}
答案 0 :(得分:0)
要粗略地从输入字段中获取值,您可以使用ref
机制。
你应该小心:ref
与真实的DOM交互,而不是虚拟的React DOM。
详细了解the official docs中的ref
。
class Form extends React.Component {
handleSubmit = (e) => {
e.preventDefault();
console.log('Values are', this.firstName.value, this.lastName.value);
}
render() {
return (
<form className="custom-form" onSubmit={this.handleSubmit}>
<input
type="text"
name="first_name"
value="John"
ref={(input) => { this.firstName = input; }}
/>
<input
type="text"
name="last_name"
value="Doe"
ref={(input) => { this.lastName = input; }}
/>
<button type="submit">Submit</button>
</form>
);
}
};
const App = () => (
<div>
<Form />
</div>
);
ReactDOM.render(<App />, document.getElementById('react'));
.custom-form {
display: block;
padding: 10px;
}
.custom-form > input {
display: block;
margin-top: 10px;
padding: 5px 10px;
border: 1px solid #ddd;
border-radius: 3px;
}
.custom-form > button {
display: block;
margin-top: 10px;
padding: 5px 10px;
background: #fff;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="react"></div>