hoc修饰过后的Input组件在Form中的使用

  1. 前置条件
    1. React@ V < 16.3
  2. 需求
    1. 对Form表单中Input组件进行全部只读/局部只读状态设置
  3. 解决方法
    1. context + hoc
      1.

       ```jsx
       import React, {createContext} from 'react'
       
       const defaultContext = {
           disabled: false,
           // setDisabled: () => {},
       }
       
       export const {Provider, Consumer} = createContext(defaultContext)
       
       const WithFormStatusHoc = (_component) => {
           const Component = _component
           return (props, ref) => {
               return (
                   <Consumer>
                       {({disabled}) => (
                           <div ref={ref}>
                               <Component disabled={disabled} {...props} />
                           </div>
                       )}
                   </Consumer>
               )
           }
       }
       
       export default WithFormStatusHoc
       ```
      
    2. hoc修饰
      1.

      ```jsx
      import {Col, Row, Form, Card, Input as AntInput, Select as AntSelect} from 'antd'
      
      const {Option} = AntSelect
      const Input = forwardRef(WithFormStatusHoc(AntInput))
      const Select = forwardRef(WithFormStatusHoc(AntSelect))
      ```
      
    3. 通过 Provider 来设置 hoc在表单中生效的范围

  4. 关注点
    1. 经hoc修饰后的组件为自定义控件,需要forwardRef来传递ref
posted @ 2022-06-01 12:00  Mmonologue  阅读(36)  评论(0)    收藏  举报