I am trying to reproduce the antd Form example in https://github.com/ant-design/ant-design/blob/master/components/form/demo/horizontal-login.md
Replacing React.createClass with extends React.Component but I am getting a Uncaught TypeError: Cannot read property 'getFieldDecorator' of undefined
with the following code:
import { Form, Icon, Input, Button } from 'antd';
const FormItem = Form.Item;
export default class HorizontalLoginForm extends React.Component {
constructor(props) {
super(props);
}
handleSubmit(e) {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
},
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form inline onSubmit={this.handleSubmit}>
<FormItem>
{getFieldDecorator('userName', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input addonBefore={<Icon type="user" />} placeholder="Username" />
)}
</FormItem>
<FormItem>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }],
})(
<Input addonBefore={<Icon type="lock" />} type="password" placeholder="Password" />
)}
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">Log in</Button>
</FormItem>
</Form>
)
}
}
Looks like the missing Form.create part is causing the issue, but don't know where it fits using the extends mechanism.
How can I properly do it ?
Ant DesignIt's great for building React apps quickly since it has a set of high-quality React components and offers robust support for browsers and server-side rendering.
@vladimirimp is on the right track, but there are 2 issues with the chosen answer.
Form.create()) should not be called in the render method.myHorizontalLoginForm) to start with capital letters.To fix this, we just need to change our default export of HorizontalLoginForm:
class HorizontalLoginForm extends React.Component { /* ... */ }
export default Form.create()(HorizontalLoginForm);
Then we can use HorizontalLoginForm directly without needing to set it to a new variable. (but if you did set it to a new variable, you would want to name that variable MyHorizontalLoginForm or anything else that starts with a capital letter).
When you wish to include your form class in parent component you must first create form, for example in parent components render method:
...
render() {
...
const myHorizontalLoginForm = Form.create()(HorizontalLoginForm);
...
return (
...
<myHorizontalLoginForm />
)
}
Be sure to import your HorizontalLoginForm class in the parent class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With