我正在使用Reactjs中的semantic-ui创建一个登录表单。请找到以下代码:
登录表单本身:
import React from 'react';
import { Form, Button } from 'semantic-ui-react';
const LoginPage = ({ email, password, handleChange, handleSubmit, errors }) => (
<Form onSubmit={handleSubmit}>
<Form.Field>
<label htmlFor="email">Email:</label>
<input
type="email"
name="email"
id="email"
placeholder="example@example.com"
value={email}
onChange={(e) => handleChange(e)}
/>
</Form.Field>
<Form.Field>
<label htmlFor="password">Password:</label>
<input
type="password"
name="password"
id="password"
value={password}
onChange={(e) => handleChange(e)}
/>
</Form.Field>
<Button primary> Login </Button>
</Form>
);
export default LoginPage;
登录容器(父组件)如下:
import React, { Component } from 'react';
import { LoginPage } from '../components';
import Validator from 'validator';
class Login extends Component {
constructor(props) {
super(props)
this.state = {
data: {
email: '',
password: ''
},
loading: false,
errors: {}
}
}
handleChange = (e) => {
this.setState({
data: { ...this.state.data, [e.target.name]: e.target.value }
});
}
handleSubmit = (values) => {
console.log(values);
const errors = this.validate(this.state.data);
this.setState({
errors: errors
})
}
validate = (data) => {
const errors = {};
if (!Validator.isEmail(data.email)) errors.email = "Invalid Email";
if (!data.password) errors.password = "Password cannot be blank";
return errors;
}
render() {
return (
<LoginPage
email={this.state.data.email}
password={this.state.data.password}
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
errors={this.state.errors}
/>
)
}
}
export default Login;
当我尝试在父组件的handleSubmit函数中控制日志值时,它总是返回代理对象而不是表单值或表单数据。
Proxy {dispatchConfig: {…}, _targetInst: ReactDOMComponent, isDefaultPrevented: ƒ, isPropagationStopped: ƒ, _dispatchListeners: ƒ, …}
有谁能让我知道我哪里出错?
由于
答案 0 :(得分:0)
“Proxy”对象似乎是Event
对象。的确是semantic-ui docs say
我们像处理香草的React一样处理数据。有关更多信息,请参阅React的受控组件文档。
这里是the vanilla react example,它指的是:
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
因此,使用此库,您自己有责任从州/商店检索表单数据,它不会自动传递给onSubmit
。
handleSubmit = (e) => {
console.log(e);
const errors = this.validate(this.state.data);
this.setState({
errors: errors
})
}
所以实际上它是正确的,因为你没有在任何地方使用这个参数e
/ values
。您只对日志和变量名称感到困惑。你可以简单地省略它。