Quellcode durchsuchen

feat: editForm组件自动聚焦

lanjianrong vor 5 Jahren
Ursprung
Commit
e66b7f05a4

+ 15 - 6
.eslintrc.js

@@ -6,17 +6,26 @@ module.exports = {
     REACT_APP_ENV: true
   },
   rules: {
-    'semi': ['error', 'never'],
+    semi: ['error', 'never'],
     'no-multiple-empty-lines': [1, { max: 2 }],
     'comma-dangle': [2, 'never'],
     'react/prop-types': 0,
     'spaced-comment': 'error',
     // 'array-bracket-spacing': ['error', 'always'], // 和prettier冲突
     'object-curly-spacing': ['error', 'always'],
-    "react/self-closing-comp": ["error", {
-      "component": true,
-      "html": true
-    }],
-    'react-hooks/exhaustive-deps': 0
+    'react/self-closing-comp': [
+      'error',
+      {
+        component: true,
+        html: true
+      }
+    ],
+    'react-hooks/exhaustive-deps': 0,
+    'no-unused-expressions': [
+      'error',
+      {
+        allowShortCircuit: true
+      }
+    ]
   }
 }

+ 13 - 8
src/components/EditableForm/editableFormItem.jsx

@@ -21,15 +21,18 @@ const EditableFormItem = ({
   const [editing, setEditing] = useState(false)
   const iRef = useRef(null)
   const [val, setVal] = useState('')
+  const [extraVal, setExtraVal] = useState('')
   const { Option } = Select
   useEffect(() => {
     setVal('')
+    setExtraVal('')
   }, [])
   useEffect(() => {
-    // 处于编辑状态自动聚焦
-    if (editing && editCellType !== 'cascader') {
+    // 处于编辑状态自动聚焦, 级联有问题暂无解决办法
+    if (editing && iRef.current) {
       iRef.current.focus()
     }
+
     // 对级联数据初始化, key一定要是district!!
     if (editCellType === 'cascader' && record) {
       dispatch({
@@ -68,12 +71,13 @@ const EditableFormItem = ({
     }
   }
   const save = async e => {
-    const { value } = e.currentTarget
+    const { value, local = '' } = e.currentTarget
     if (value === record || !value) {
       return
     }
-    setVal(value)
     await handleConfirm(value)
+    local && setExtraVal(local)
+    setVal(value)
     toggleEdit()
   }
 
@@ -94,10 +98,11 @@ const EditableFormItem = ({
       case 'cascader':
         cell = (
           <LazyCascader
-            // ref={iRef}
+            ref={iRef}
             defaultValue={val}
             className="zh-width-100P"
-            onChange={value => save({ currentTarget: { value } })}
+            onBlur={save}
+            onChange={(value, local) => save({ currentTarget: { value, local } })}
           />
         )
         break
@@ -106,7 +111,7 @@ const EditableFormItem = ({
           <Select
             defaultValue={val}
             ref={iRef}
-            // onBlur={save}
+            onBlur={save}
             onChange={value => save({ currentTarget: { value } })}
             className="zh-width-100P">
             {options}
@@ -139,7 +144,7 @@ const EditableFormItem = ({
   } else {
     let content = val
     if (editCellType === 'cascader') {
-      content = dataSource.local
+      content = extraVal || dataSource.local
     }
     cell = (
       <div className="editable-cell-value-wrap" onClick={toggleEdit}>

+ 21 - 10
src/components/LazyCascader/LazyCascader.jsx

@@ -1,8 +1,8 @@
 import { Cascader } from 'antd'
-import React, { useEffect } from 'react'
+import React, { forwardRef, useEffect, useRef } from 'react'
 import { connect } from 'dva'
 
-const LazyCascader = props => {
+const CLazyCascader = props => {
   const { options, dispatch, onChange, ...resetProps } = props
   // console.log(props.defaultValue)
   useEffect(() => {
@@ -11,15 +11,21 @@ const LazyCascader = props => {
         type: 'district/fetch'
       })
     }
+    // if (refinstance && refinstance.current) {
+    //   refinstance.current.focus()
+    // }
   }, [])
 
-  const triggerChange = value => {
+  const triggerChange = (value, local = '') => {
     if (onChange) {
-      onChange(value)
+      onChange(value, local)
     }
   }
-  const handleOnChange = value => {
-    triggerChange(value)
+  const handleOnChange = (value, selectedOptions) => {
+    const local = selectedOptions.reduce((prev, curr) => {
+      return `${prev}${prev ? ',' : ''}${curr.name}`
+    }, '')
+    triggerChange(value, local)
   }
 
   const loadData = selectedOptions => {
@@ -38,15 +44,20 @@ const LazyCascader = props => {
       {...resetProps}
       placeholder="省/市/区"
       options={options}
+      ref={refinstance}
       onChange={handleOnChange}
       loadData={loadData}
-      // allowClear={false}
       fieldNames={{ label: 'name', value: 'id' }}
       // changeOnSelect
     />
   )
 }
-
-export default connect(({ district }) => ({
+const LazyCascader = connect(({ district }) => ({
   options: district.data
-}))(LazyCascader)
+}))(CLazyCascader)
+export default forwardRef((props, ref) => {
+  return <LazyCascader {...props} refinstance={ref} />
+})
+// export default connect(({ district }) => ({
+//   options: district.data
+// }))(LazyCascader)

+ 15 - 6
src/models/district.js

@@ -21,16 +21,25 @@ export default {
       }
     },
     *fetchWithValues({ payload = [] }, { call, put }) {
-      for (let i = 0; i < payload.length - 1; i++) {
-        const parentId = payload[i]
-        const response = yield call(queryDistrict, { parentId })
+      const provinceId = payload[0] //
+      const cityId = payload[1]
+      const { code = -1, data = [] } = yield call(queryDistrict, { parentId: provinceId })
+      if (code === consts.RET_CODE.SUCCESS) {
+        const response = yield call(queryDistrict, { parentId: cityId })
         if (response && response.code === consts.RET_CODE.SUCCESS) {
+          const newData = data.map(item => {
+            const newItem = { ...item }
+            if (item.id === cityId) {
+              newItem.children = response.data
+            }
+            return newItem
+          })
           yield put({
             type: 'changeState',
             payload: {
-              data: response.data,
-              parentId,
-              level: i + 1
+              data: newData,
+              parentId: provinceId,
+              level: 1
             }
           })
         }

+ 0 - 0
src/models/refresh.js


+ 43 - 3
src/pages/Customer/Test/index.jsx

@@ -1,9 +1,43 @@
-import React from 'react'
-import { Card } from 'antd'
+import React, { useRef } from 'react'
+import { Button, Card, Cascader } from 'antd'
 import EditableForm from '@/components/EditableForm'
 
 const Test = () => {
-
+  const iRef = useRef(null)
+  const options = [
+    {
+      value: 'zhejiang',
+      label: 'Zhejiang',
+      children: [
+        {
+          value: 'hangzhou',
+          label: 'Hangzhou',
+          children: [
+            {
+              value: 'xihu',
+              label: 'West Lake'
+            }
+          ]
+        }
+      ]
+    },
+    {
+      value: 'jiangsu',
+      label: 'Jiangsu',
+      children: [
+        {
+          value: 'nanjing',
+          label: 'Nanjing',
+          children: [
+            {
+              value: 'zhonghuamen',
+              label: 'Zhong Hua Men'
+            }
+          ]
+        }
+      ]
+    }
+  ]
   const record = {
     address: '珠海',
     clientName: '啊实打实大',
@@ -27,9 +61,15 @@ const Test = () => {
       span: 24
     }
   ]
+  const onClick = () => {
+    console.log(iRef)
+    iRef.current.input.focus()
+  }
   return (
     <Card bordered={false}>
       <EditableForm dataSource={record} columns={columns} />
+      <Button onClick={onClick}>click</Button>
+      <Cascader ref={iRef} options={options} />
     </Card>
   )
 }