react+antd: Global Settings form Form is not Editable

Posted by chenci on Wed, 02 Oct 2019 03:21:56 +0200

When editing a page, a requirement is "Content is not editable in a specified state"

Solution 1: Add disable attributes to <Input>, <Select>... for each <Input>, <Select>.

This scheme may not be very convenient in the case of more form content, so Miss Gu helped me to think about the second scheme.

Solution 2: Encapsulate a component to set disable globally, as follows

Encapsulate a higher-order component (. / Input)

import React, { useContext, createContext } from "react";

export const FormDisabledContext = createContext({
  disabled: false,
  setDisabled: () => {}
});

function CustomFormItemHoc(component) {
  const Component = component;
  return function CustomItem(props) {
    const { disabled } = useContext(FormDisabledContext);
    return <Component disabled={disabled} {...props} />;
  };
}

export default CustomFormItemHoc;

Component use:

import React from "react";
import ReactDOM from "react-dom";
import {
  Form,
  Icon,
  Input as AntdInput,
  Button,
  Checkbox as AntdCheckbox
} from "antd";
import CustomFormItemHoc, { FormDisabledContext } from "./Input";

const Input = CustomFormItemHoc(AntdInput);
const Checkbox = CustomFormItemHoc(AntdCheckbox);

class NormalLoginForm extends React.Component {
  state = {
    disabled: false
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <FormDisabledContext.Provider
          value={{
            disabled: this.state.disabled
          }}
        >
          <Form onSubmit={this.handleSubmit} className="login-form">
            <Form.Item>
              ...
            </Form.Item>
          </Form>
        </FormDisabledContext.Provider>
        <Checkbox onChange={this.setDisabled}>disabled</Checkbox>
      </div>
    );
  }
}

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);

export default WrappedNormalLoginForm;

Teacher Code By ku

Topics: React