“This is the second day of my participation in the First Challenge 2022.

preface

This is the second update of 2022. Before, I didn’t like to record some problems I encountered in my work. I always thought that my brain capacity could remember all of them. Now I feel it is necessary to sum up the problems and thoughts encountered in the work, and output them into writing, so as to leave a record for the future work to avoid stepping on the pit again.

Ok, today’s question is: How to encapsulate an optional button component?

Everything has a source, demand can not be created out of thin air, someone must have encountered or used such a similar component, think it can be applied to our business requirements, so he can not deny the need to walk away (no requirement is simple).

Demand background

Since we used Vue technology stack for development at the beginning of our work, Element UI framework was naturally selected as the corresponding UI framework. Therefore, when we changed the technology stack to React later, some component effects of Antd we chose were not provided. For example, Element’s Checkbox component provides a button-style Checkbox effect component, but Antd does not.

The development of

Do it! Do it! Do it! Let’s take a look at the UI design diagram and see how you can do it:

Consider: it is used as a query condition, so how can we write components to be used in the Form? The idea is to make components controlled components so that they can be used in conjunction with forms, reducing other development time.

Controlled components: In React, mutable state is usually stored in the component’s state properties and can only be updated using setState(). The React component that renders the form also controls what happens to the form when the user enters it later. This way of changing the value of a form element controlled by React is called a controlled component.

Uncontrolled components: The form data is handled by the DOM itself. namelyFrom the setState ()Similar to traditional HTML form input, the input value displays the latest valuerefGet the form value from the DOM.

Now that I have thought clearly enough, there should be no problem.

Create reactCheckbox. TSX file:

import React from 'react'; Import './style.less' // default professional const List: any[] = [{id: 1, value: 'building ', label:' building '}, {id: 2, value: 'structure ', label: 'and'}, {id: 3, value: 'water supply and drainage, label:' water '}, {id: 4, value: 'electrical, label:' electricity '}, {id: 5, value: hvac, label: 'warm'}] interface Data {value: a string | number; label: string; isActive? : boolean; } interface ReactCheckBoxProps { data? : Data[]; // If there is no data source passed in by the parent, use the majorList value? : any[]; // The selected value size? : string; // Size size onChange? : (checkList: any[], checked: boolean) => void; /** * React * props * @constructor */ const ReactCheckBox = (props: ReactCheckBoxProps) => { const {data = List, value = [], size = 'default', onChange = (checkList: any[]) => {}} = props; /** * check @param value @param checked */ const checkItem = (val: string, checked: boolean) => { let newCheckedList:any[] = [...value]; newCheckedList = checked ? [...newCheckedList, val] : newCheckedList.filter(v => v ! = val); onChange(newCheckedList, true); } return ( <div className={["bit-group-wrap", size].join(' ')}> {data.map((item: any, index: number) => <div className={ [ "bit-group-item", value.includes(item.value) ? 'is-checked' : '', item.isActive ? "is-actived" : '' ].join(' ') } onClick={() => checkItem(item.value, ! value.includes(item.value))} key={index} > {item.label} </div> )} </div> ) } export default ReactCheckBox;Copy the code

Create style.less style file:

.bit-group-wrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
  height: 30px;

  .bit-group-item {
    line-height: 1;
    font-weight: 500;
    white-space: nowrap;
    vertical-align: middle;
    cursor: pointer;
    background: #fff;
    border: 1px solid #dcdfe6;
    border-left: 0;
    color: #606266;
    -webkit-appearance: none;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 0;
    transition: all .3s cubic-bezier(.645, .045, .355, 1);
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    padding: 8px 20px;
    font-size: 14px;
    border-radius: 0;
  }

  .bit-group-item:first-child {
    border-left: 1px solid #dcdfe6;
  }

  .is-checked {
    color: #fff;
    background-color: #409eff;
    border-color: #409eff;
    box-shadow: -1px 0 0 0 #8cc5ff;
  }

  .is-checked:first-child {
    border-left-color: #409eff;
  }

  .is-actived {
    color: #5D5D5D;
    background-color: #E3E6EE;
    border-color: rgba(0, 0, 0, .15);
    box-shadow: -1px 0 0 0 rgba(0, 0, 0, .15);
  }
}

.small {
    height: 24px;
}
.default {
    height: 30px;
}

.large {
    height: 40px;
}
Copy the code

At this point, the related code of the component has been written, you can see that the code structure and logic is not very complex, it is a combination of multi-choice functions and check style. The value and onChange attributes are added to the code to allow the component to be used within the Form, making it a controlled component.

Usage:

1) Import ReactCheckBox from ".. /.. /.. /component/ReactCkeckBox/ReactCheckBox"; Const List: any[] = [{value: 1, label: 'general '}, {value: 2, label:' important '}, {value: 3, label: }] <Form Form ={Form}> < form. Item label=" professional: "Name ="majors" initialValue={[' building ', 'structure ',' Electrical ', 'HVAC ']}> <ReactCheckBox /> </ form. Item> < form. Item label=" " name="levels" initialValue={[1, 2]}> <ReactCheckBox data = {List} /> </Form.Item> </Form> const monthList: Any [] = [{value: '2021-09-17 00:00:00', label: '9 ', isActive: false}, {value: '2021-10-17 00:00:00', label: '10月', isActive: false}, {value: '21-11-17 00:00:00', label: '11月', isActive: false}, {value:' 21-11-17 00:00:00', label: '11月', isActive: false}, {value: '2021-12-17 00:00:00', label: '12月', isActive: false}, {value: '2022-01-17 00:00:00', label: '1月', isActive: True}, {value: '2022-02-17 00:00:00', label: '2月', isActive: true}, {value: '2022-03-17 00:00:00', label: '3月', isActive: false}, {value: '2022-04-17 00:00:00', label: '4月', isActive: false}, {value: '2022-04-17 00:00:00', label: '4月', isActive: false}, {value: '2022-05-17 00:00:00', Label: '5月', isActive: },] <Form Form ={tableForm}> < form. Item label=" "Name ="filterMonth"> <ReactCheckBox onChange={() => {// emit({actionId: 'XXXXX ', action: ''}) }} data={monthList}/> </Form.Item> <Form form={form}>Copy the code

Effect:

API:

parameter instructions type
data The data source any[]
size The size small/default/large
value Specifies the selected option string[]
onChange Change when the callback function function(checkList: any[], checked: boolean)

All things are difficult at the beginning. In fact, in the absence of the support of existing components, the partners in the group will subjectively think that there is a certain difficulty, but after careful consideration, there will be a bright future. There is already a corresponding package for others to use on NPM, but it is not enough for reuse. The updated version will be upgraded by iteration to make it better applicable.

Past wonderful articles

  • 2022 First update: 3 Progress bar effects in front end projects
  • Front-end Tech Trends 2022: You don’t come in and see how to earn it a small target?
  • If ancient have programmers writing summaries, probably is such | 2021 year-end summary
  • Front-end development specifications in front end team practice
  • Javascript high-level constructors
  • Javascript high-level inheritance
  • Recursion and closure

After the language

Guys, if you find this article helpful, click 👍 or ➕. In addition, if there are questions or do not understand the part of this article, you are welcome to comment on the comment section, we discuss together.