经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JSJS库框架 » JavaScript » 查看文章
ant-design form
来源:cnblogs  作者:MyNodeJs  时间:2018/9/28 16:51:49  对本文有异议

表单配置

示例代码

  1. import { Form } from 'antd';
  2. const FormItem = Form.Item;
  3. class NormalLoginForm extends React.Component {
  4. handleSubmit = (e) => {
  5. e.preventDefault();
  6. this.props.form.validateFields((err, values) => {
  7. if (!err) {
  8. console.log('Received values of form: ', values);
  9. }
  10. });
  11. }
  12. render() {
  13. const { getFieldDecorator } = this.props.form;
  14. return (
  15. <Form onSubmit={this.handleSubmit} className="login-form">
  16. <FormItem>
  17. {getFieldDecorator('userName', {
  18. rules: [{ required: true, message: 'Please input your username!' }],
  19. })(
  20. <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
  21. )}
  22. </FormItem>
  23. <FormItem>
  24. {getFieldDecorator('password', {
  25. rules: [{ required: true, message: 'Please input your Password!' }],
  26. })(
  27. <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
  28. )}
  29. </FormItem>
  30. <FormItem>
  31. {getFieldDecorator('remember', {
  32. valuePropName: 'checked',
  33. initialValue: true,
  34. })(
  35. <Checkbox>Remember me</Checkbox>
  36. )}
  37. <a className="login-form-forgot" href="">Forgot password</a>
  38. <Button type="primary" htmlType="submit" className="login-form-button">
  39. Log in
  40. </Button>
  41. Or <a href="">register now!</a>
  42. </FormItem>
  43. </Form>
  44. );
  45. }
  46. }
  47. const WrappedNormalLoginForm = Form.create()(NormalLoginForm);
  48. ReactDOM.render(<WrappedNormalLoginForm />, mountNode);

FormItem

const FormItem = Form.Item;
封装过的表单域

  1. <FormItem {...formItemLayout} label="Name">
  2. {getFieldDecorator('username', {
  3. rules: [{
  4. required: true,
  5. message: 'Please input your name',
  6. }],
  7. })(
  8. <Input placeholder="Please input your name" />
  9. )}
  10. </FormItem>

支持label属性
通过getFieldDecorator返回封装好的表单域
getFieldDecorator(id,options)
id唯一,
options.initialValue 子节点的初始值
options.rules 校验规则
options.valuePropName 子节点的值的属性,如 Switch 的是 'checked'

获取表单域值

  1. this.props.form.getFieldValue('password')

表单域值的校验

  1. this.props.form.validateFields((err, values) => {
  2. if (!err) {
  3. console.log('Received values of form: ', values);
  4. }
  5. });

传一个函数,第二个参数是表单域值的集合

重置表单域的值

  1. this.props.form.resetFields();

setFieldsValue

使用 setFieldsValue 来动态设置其他控件的值。

  1. this.props.form.setFieldsValue({
  2. note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
  3. });

循环表单

  1. import { Form, Row, Col, Input, Button, Icon } from 'antd';
  2. const FormItem = Form.Item;
  3. class AdvancedSearchForm extends React.Component {
  4. state = {
  5. expand: false,
  6. };
  7. handleSearch = (e) => {
  8. e.preventDefault();
  9. this.props.form.validateFields((err, values) => {
  10. console.log('Received values of form: ', values);
  11. });
  12. }
  13. handleReset = () => {
  14. this.props.form.resetFields();
  15. }
  16. toggle = () => {
  17. const { expand } = this.state;
  18. this.setState({ expand: !expand });
  19. }
  20. // To generate mock Form.Item
  21. getFields() {
  22. const count = this.state.expand ? 10 : 6;
  23. const { getFieldDecorator } = this.props.form;
  24. const children = [];
  25. for (let i = 0; i < 10; i++) {
  26. children.push(
  27. <Col span={8} key={i} style={{ display: i < count ? 'block' : 'none' }}>
  28. <FormItem label={`Field ${i}`}>
  29. {getFieldDecorator(`field-${i}`, {
  30. rules: [{
  31. required: true,
  32. message: 'Input something!',
  33. }],
  34. })(
  35. <Input placeholder="placeholder" />
  36. )}
  37. </FormItem>
  38. </Col>
  39. );
  40. }
  41. return children;
  42. }
  43. render() {
  44. return (
  45. <Form
  46. className="ant-advanced-search-form"
  47. onSubmit={this.handleSearch}
  48. >
  49. <Row gutter={24}>{this.getFields()}</Row>
  50. <Row>
  51. <Col span={24} style={{ textAlign: 'right' }}>
  52. <Button type="primary" htmlType="submit">Search</Button>
  53. <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
  54. Clear
  55. </Button>
  56. <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}>
  57. Collapse <Icon type={this.state.expand ? 'up' : 'down'} />
  58. </a>
  59. </Col>
  60. </Row>
  61. </Form>
  62. );
  63. }
  64. }
  65. const WrappedAdvancedSearchForm = Form.create()(AdvancedSearchForm);
  66. ReactDOM.render(
  67. <div>
  68. <WrappedAdvancedSearchForm />
  69. <div className="search-result-list">Search Result List</div>
  70. </div>,
  71. mountNode
  72. );

动态增减表单

  1. import { Form, Input, Icon, Button } from 'antd';
  2. const FormItem = Form.Item;
  3. let uuid = 0;
  4. class DynamicFieldSet extends React.Component {
  5. remove = (k) => {
  6. const { form } = this.props;
  7. // can use data-binding to get
  8. const keys = form.getFieldValue('keys');
  9. // We need at least one passenger
  10. if (keys.length === 1) {
  11. return;
  12. }
  13. // can use data-binding to set
  14. form.setFieldsValue({
  15. keys: keys.filter(key => key !== k),
  16. });
  17. }
  18. add = () => {
  19. const { form } = this.props;
  20. // can use data-binding to get
  21. const keys = form.getFieldValue('keys');
  22. const nextKeys = keys.concat(uuid);
  23. uuid++;
  24. // can use data-binding to set
  25. // important! notify form to detect changes
  26. form.setFieldsValue({
  27. keys: nextKeys,
  28. });
  29. }
  30. handleSubmit = (e) => {
  31. e.preventDefault();
  32. this.props.form.validateFields((err, values) => {
  33. if (!err) {
  34. console.log('Received values of form: ', values);
  35. }
  36. });
  37. }
  38. render() {
  39. const { getFieldDecorator, getFieldValue } = this.props.form;
  40. const formItemLayout = {
  41. labelCol: {
  42. xs: { span: 24 },
  43. sm: { span: 4 },
  44. },
  45. wrapperCol: {
  46. xs: { span: 24 },
  47. sm: { span: 20 },
  48. },
  49. };
  50. const formItemLayoutWithOutLabel = {
  51. wrapperCol: {
  52. xs: { span: 24, offset: 0 },
  53. sm: { span: 20, offset: 4 },
  54. },
  55. };
  56. getFieldDecorator('keys', { initialValue: [] });
  57. const keys = getFieldValue('keys');
  58. const formItems = keys.map((k, index) => {
  59. return (
  60. <FormItem
  61. {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
  62. label={index === 0 ? 'Passengers' : ''}
  63. required={false}
  64. key={k}
  65. >
  66. {getFieldDecorator(`names[${k}]`, {
  67. validateTrigger: ['onChange', 'onBlur'],
  68. rules: [{
  69. required: true,
  70. whitespace: true,
  71. message: "Please input passenger's name or delete this field.",
  72. }],
  73. })(
  74. <Input placeholder="passenger name" style={{ width: '60%', marginRight: 8 }} />
  75. )}
  76. {keys.length > 1 ? (
  77. <Icon
  78. className="dynamic-delete-button"
  79. type="minus-circle-o"
  80. disabled={keys.length === 1}
  81. onClick={() => this.remove(k)}
  82. />
  83. ) : null}
  84. </FormItem>
  85. );
  86. });
  87. return (
  88. <Form onSubmit={this.handleSubmit}>
  89. {formItems}
  90. <FormItem {...formItemLayoutWithOutLabel}>
  91. <Button type="dashed" onClick={this.add} style={{ width: '60%' }}>
  92. <Icon type="plus" /> Add field
  93. </Button>
  94. </FormItem>
  95. <FormItem {...formItemLayoutWithOutLabel}>
  96. <Button type="primary" htmlType="submit">Submit</Button>
  97. </FormItem>
  98. </Form>
  99. );
  100. }
  101. }
  102. const WrappedDynamicFieldSet = Form.create()(DynamicFieldSet);
  103. ReactDOM.render(<WrappedDynamicFieldSet />, mountNode);
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号