ReactAnt Design 5.0 构建通用后台管理系统界面

Posted EvilChan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ReactAnt Design 5.0 构建通用后台管理系统界面相关的知识,希望对你有一定的参考价值。

事前准备

  • node
  • npm
  • vscode / webstorm

前端开发环境准备

项目初始化

npm create vite
√ Project name: » general-admin-system-ui
√ Select a framework: » React
√ Select a variant: » TypeScript + SWC

cd general-admin-system-ui
npm install
code .

依赖清单


  "dependencies": 
    "@ant-design/icons": "^5.0.1",
    "@ant-design/pro-components": "^2.4.4",
    "antd": "^5.4.5",
    "axios": "^1.3.6",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.10.0"
  ,

开发依赖清单


  "devDependencies": 
    "@types/node": "^18.16.0",
    "@types/react": "^18.0.28",
    "@types/react-dom": "^18.0.11",
    "@typescript-eslint/eslint-plugin": "^5.57.1",
    "@typescript-eslint/parser": "^5.57.1",
    "@vitejs/plugin-react-swc": "^3.0.0",
    "eslint": "^8.38.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.3.4",
    "typescript": "^5.0.2",
    "vite": "^4.3.0"
  

tsconfig.json 追加配置


  "compilerOptions": 
    "baseUrl": ".",
    "paths": 
      "@/*": ["src/*"],
      "@@/*": ["*"]
    
  

vite.config.ts

import  defineConfig  from \'vite\'
import react from \'@vitejs/plugin-react-swc\'
import  resolve  from \'path\'

// https://vitejs.dev/config/
export default defineConfig(
  // 与tsconfig.json的paths关联
  resolve: 
    alias: 
      \'@\': resolve(__dirname, \'./src\'),
      \'@@\': __dirname,
    ,
  ,
  server: 
    port: 9999,
  ,
  plugins: [react()],
)

.editorconfig(可选)

# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = false

[*.css]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.js,jsx,ts,tsx,json,cjs]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

.prettierrc.js(可选)

module.exports = 
  singleQuote: true,
  semi: false,

vscode settings.json推荐配置(可选)


  "[javascript]": 
    "editor.maxTokenizationLineLength": 2500,
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": 
      "source.organizeImports": true
    
  ,
  "[javascriptreact]": 
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": 
      "source.organizeImports": true
    
  ,
  "[typescript]": 
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": 
      "source.organizeImports": true
    
  ,
  "[typescriptreact]": 
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
    "editor.codeActionsOnSave": 
      "source.organizeImports": true
    
  ,
  "[json]": 
    "editor.quickSuggestions": 
      "strings": true
    ,
    "editor.suggest.insertMode": "replace",
    "gitlens.codeLens.scopes": ["document"],
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
  ,
  "[jsonc]": 
    "editor.quickSuggestions": 
      "strings": true
    ,
    "editor.suggest.insertMode": "replace",
    "gitlens.codeLens.scopes": ["document"],
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true
  

项目结构

general-admin-system-ui
|-- index.html
|-- package-lock.json
|-- package.json
|-- public
|   `-- vite.svg
|-- src
|   |-- App.tsx
|   |-- assets
|   |   `-- react.svg
|   |-- main.tsx
|   `-- vite-env.d.ts
|-- tree.md
|-- tree.txt
|-- tsconfig.json
|-- tsconfig.node.json
`-- vite.config.ts

用ant-design在react js中提交后清除表单输入字段值

【中文标题】用ant-design在react js中提交后清除表单输入字段值【英文标题】:Clear form input field values after submitting in react js with ant-design 【发布时间】:2019-05-23 23:24:13 【问题描述】:

我使用 react 创建了一个注册页面。在那里,我使用了以下注册表单。 https://ant.design/components/form。所有验证均已正确处理,成功尝试后用户可以注册到系统。我遇到的唯一问题是,提交后无法清除表单输入字段值。

我已经实现了一种将表单字段值清除为空的方法。但它不起作用。而且我在***中尝试了以前的类似问题,但仍然无法为我找到一个可行的问题。原因可能是因为我使用的是 ant 设计模板。

this.setState(
        confirmDirty: false,
        autoCompleteResult: [],
        userName: '',
        email: '',
        experience: [],
        password: ''
)

上面的代码是清除输入值。但它不起作用,所有表单输入字段值仍然保存。下面是部分注册表单代码。

class RegistrationForm extends React.Component 
state = 
    confirmDirty: false,
    autoCompleteResult: [],
    userName: '',
    email: '',
    experience: [],
    password: ''
;
//below form is inside the render method and return 
<Form onSubmit=this.handleSubmit>
  <FormItem
    ...formItemLayout
    label="E-mail"
  >
  getFieldDecorator('email', 
     rules: [
        type: 'email', message: 'The input is not valid E-mail!',
     , 
        required: true, message: 'Please input your E-mail!',
     ],
     )(
        <Input />
     )
  </FormItem>
</Form>
  handleSubmit = (e) => 
      e.preventDefault();
      this.props.form.validateFieldsAndScroll((err, values) => 
        if (!err) 
          //submission done
          //then execute the above code which I mentioned previously in the question, to reset the input fields value

        
      );
  
  

我可能在哪里出错,我该如何解决?

【问题讨论】:

请分享完整的组件代码以更好地理解您的问题 请分享使用此状态清除字段的代码。 用更多代码更新了问题。 @HemadriDasari 【参考方案1】:

我们可以使用蚂蚁设计library给出的表单道具中的resetFields函数清除表单数据。

表单提交成功后,使用this.props.form.resetFields()清除表单中的数据。

代码:

const  Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete,  = antd;

const  Option  = Select;
const AutoCompleteOption = AutoComplete.Option;

class RegistrationForm extends React.Component 
  state = 
    confirmDirty: false,
    autoCompleteResult: [],
  ;

  handleSubmit = (e) => 
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => 
      if (!err) 
        console.log('Received values of form: ', values);
      
    );
  

  handleConfirmBlur = (e) => 
    const value = e.target.value;
    this.setState( confirmDirty: this.state.confirmDirty || !!value );
  

  render() 
    const  getFieldDecorator  = this.props.form;
    const  autoCompleteResult  = this.state;

    const formItemLayout = 
      labelCol: 
        xs:  span: 24 ,
        sm:  span: 8 ,
      ,
      wrapperCol: 
        xs:  span: 24 ,
        sm:  span: 16 ,
      ,
    ;
    const tailFormItemLayout = 
      wrapperCol: 
        xs: 
          span: 24,
          offset: 0,
        ,
        sm: 
          span: 16,
          offset: 8,
        ,
      ,
    ;

    return (
      <Form onSubmit=this.handleSubmit>
        <Form.Item
          ...formItemLayout
          label="E-mail"
        >
          getFieldDecorator('email', 
            rules: [
              type: 'email', message: 'The input is not valid E-mail!',
            , 
              required: true, message: 'Please input your E-mail!',
            ],
          )(
            <Input />
          )
        </Form.Item>
        <Form.Item
          ...formItemLayout
          label="Password"
        >
          getFieldDecorator('password', 
            rules: [
              required: true, message: 'Please input your password!',
            , 
              validator: this.validateToNextPassword,
            ],
          )(
            <Input type="password" />
          )
        </Form.Item>
        <Form.Item ...tailFormItemLayout>
          getFieldDecorator('agreement', 
            valuePropName: 'checked',
          )(
            <Checkbox>I have read the <a href="">agreement</a></Checkbox>
          )
        </Form.Item>
        <Form.Item ...tailFormItemLayout>
          <Button type="primary" htmlType="submit">Register</Button>
        </Form.Item>

        <Form.Item ...tailFormItemLayout>
          <Button onClick=e => 
this.props.form.resetFields()
                           >Clear</Button>
        </Form.Item>
      </Form>
    );
  


const WrappedRegistrationForm = Form.create()(RegistrationForm);

ReactDOM.render(<WrappedRegistrationForm />, mountNode);

Live Demo

希望对你有帮助:)

【讨论】:

还会清除表单元素中的 initialValue= 属性吗?【参考方案2】:

在函数组件中,您可以使用Form.useForm 挂钩非常轻松地访问表单。此挂钩返回的值应作为Form 组件的form 属性传递。然后,您可以在要清除表单的任何回调中调用表单上的resetFields。本示例将在提交时清除表单:

import React from 'react';
import  Button, Form, Input  from 'antd';

export default function MyFormComponent() 
  const [form] = Form.useForm();

  const submitForm = ( name, favoriteColor ) => 
    console.log(name, favoriteColor);
    form.resetFields();
  ;

  return (
    <Form
      form=form
      labelCol= span: 6 
      wrapperCol= span: 12 
      onFinish=submitForm
    >
      <Form.Item name="name" label="What is your name?">
        <Input />
      </Form.Item>
      <Form.Item name="favoriteColor" label="What is your favorite color?">
        <Input />
      </Form.Item>
      <Form.Item wrapperCol= offset: 6, span: 12 >
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );


这仅适用于 antd 4.x 及更高版本。在早期版本中,表单似乎更难处理。

【讨论】:

能否请您帮助重置 form.resetFields() 上 Radio.Group 的值;称呼。 ***.com/questions/61720143/…【参考方案3】:

非常简单的解决方案: 把这一行放在功能组件里就行了

const [form] = Form.useForm();

<Form
            form=form
            name="normal_login"
            className="login-form"
            initialValues=
            remember: true,
            
/>

之后将form 调用到onFinish() 函数中。

const onFinish=(values)=>
     
      form.resetFields();
      let array1=[];
      if(Array.isArray(array1))
        array1=values;
        localStorage.setItem(`$id`,JSON.stringify(id,...array1));
      
  

【讨论】:

【参考方案4】:

form.resetFields() 将重置所有表单字段。

重置特定表单字段form.resetFields([formItemName])

FormInstance

import React,  useState  from "react";
import  Form, Input  from "antd";

const myComp = () => 
  const [form] = Form.useForm();
  const [val, setVal] = useState("");

  const handleCancel = () => 
    form.resetFields();    //reset form
  ;

  const handleOk = async (e) => 
      form.resetFields();    //reset form
  ;

  const handelChange = async (e) => 
      setVal(e.target.value);
      if(val.length > 10) 
        form.resetFields(["textField"]); //reset particular field
      
  ;

  return (
      <Form
        form=form
        name="dynamic_ruleEdit"
        onFinish=handleOk
      >
        <Form.Item
          name="textField"
          label="Enter your details"
          rules=[
            
              message: "Enter details",
              required: true,
            ,
          ]
        >
          <Input
            value=val
            placeholder="Enter details"
            onChange=handelChange
          />
        </Form.Item>
      </Form>
  );

export default myComp;

【讨论】:

【参考方案5】:
    新建一个Button并设置onclick()。 然后在点击按钮时调用 this.props.form.resetFields() 您在上面创建的。 为此,您需要将组件导出为导出默认值 Form.create()(YourComponent);

【讨论】:

【参考方案6】:
    使用 resetForm() 重置整个表单的最简单方法。
form.resetFields()
    对于那些要更改默认值的输入,可以使用 setFieldsValue() 指定。
...
onChange=() => form.setFieldsValue( name: '' )
...

【讨论】:

以上是关于ReactAnt Design 5.0 构建通用后台管理系统界面的主要内容,如果未能解决你的问题,请参考以下文章

开源Reactant: 一个渐进式React的框架

Vue笔记-Ant Design Vue构建前端连接后端WebSocket

java规则引擎drools6.5.0中kie的概论

使用 DrawerLayout 实现 Material Design风格的侧滑

如何创建一个向后兼容iOS 5.0的新Xcode 5项目? - 错过故事板错误

thinkPHP输出sql语句(3.2和5.0通用)