This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

👉 practice makes perfect, shortage in one, success depends on forethought. Tang Han Yu, “Into Learning Solutions”

preface

Web Component is an area of interest in the front-end world. To implement it with a third-party componentized framework, you have to rely a lot on the framework itself. A lot of times we just have a few simple components, not too big, not too many, so to keep the components lightweight, Simple, we didn’t really want to use a third party framework at this point.

Let’s take a look at the implementation

The CheckBox boxes,

import


import CheckBox from '@/components/CheckBox/CheckBox';

Copy the code

Props

1. checked
  • Types: bool

  • Default value: false

  • Note: True indicates whether the command is selected

2. disabled
  • Types: bool

  • Default value: false

  • Note: Whether the check box is unavailable, true indicates that the check box is unavailable, and the check box is gray

3. indeterminate
  • Types: bool

  • Default value: false

  • Note: Whether to enable the uncertain state (that is, not all selected, checked is false; True indicates an indeterminate state, checked is false shows a little blue box in the middle.)

4. onChange
  • Type: func (required)

  • Default value: none

  • Note: Select the callback function when the state changes and enter the parameter:

  • {Boolean} newChecked indicates the newChecked status

5. className
  • Type: string | array | object (key: style name, value: bool)

  • Default value: none

  • Description: Outermost element style


<CheckBox className = {'my-class'}></CheckBox>

<CheckBox className = {['my-class1', 'my-class2']} ></CheckBox>

<CheckBox className = {{'my-class1': true}} ></CheckBox>

Copy the code

CheckBoxGroup Multi-box group

import


import CheckBoxGroup from '@/components/CheckBox/CheckBoxGroup';

Copy the code

Props

1. options
  • Type: array (required)

  • Default value: none

  • Description: Optional array


<CheckBoxGroup options = {[{label: "Option one.".value: 1}, {label: "Option 2".value: 2.disabled: true}]}></CheckBoxGroup>

Copy the code
2. value
  • Type: array

  • Default value: []

  • Note: Select an array of options value

3. disabled
  • Types: bool

  • Default value: false

  • Note: Whether the check box group is unavailable, true indicates that the check box group is unavailable, and all the check boxes in this group are gray

4. onChange
  • Type: func (required)

  • Default value: none

  • Note: The group check box selects the callback function when the state changes, and enters the parameter:

  • {Array} newGroupValue Array of new selected options

5. className
  • Type: string | array | object (key: style name, value: bool)

  • Default value: none

  • Description: Outermost element style


<CheckBoxGroup className = {'my-class'}></CheckBoxGroup>

<CheckBoxGroup className = {['my-class1', 'my-class2']} ></CheckBoxGroup>

<CheckBoxGroup className = {{'my-class1': true}} ></CheckBoxGroup>

Copy the code

To realize the CheckBox. Js

import React from 'react';
import PropTypes from 'prop-types';
// To ensure that test cases run, the utils module built into Webpack is not used
import utils from '.. /.. /js/common/utils/index.js';
import './CheckBox.scss';
/** * CheckBox CheckBox */

class CheckBox extends React.Component {
    // Check the input type
    static propTypes = {
        // Check whether (true indicates check)
        checked: PropTypes.bool,
        // Whether the check box is unavailable (true indicates that the check box is unavailable, and the check box is gray)
        disabled: PropTypes.bool,
        // Whether to enable the indeterminate state (i.e., not all checked is false; True indicates an indeterminate state, checked is false shows a little blue box in the middle.)
        indeterminate: PropTypes.bool,
        /** * Select the callback function * for state changes@param {boolean} NewChecked newChecked status */
        onChange: PropTypes.func.isRequired,
        // Outermost element style
        className: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.array,
            PropTypes.objectOf(PropTypes.bool)
        ])
    }
    // Enter the default value
    static defaultProps = {
        checked: false.disabled: false.indeterminate: false
    }
    constructor(props) {
        super(props);
        this.state = {
            // Whether the mouse floats over the component
            hover: false
        };
    }

    /** * Select the class * required for the outermost layer of the box@returns {string}* /

    getCheckboxWrapperClassName(){
        return utils.clasx(this.props.className, {
            'checkbox-wrapper': true.'checkbox-checked': this.props.checked,
            'checkbox-disabled': this.props.disabled,
            'checkbox-indeterminate': this.props.indeterminate && !this.props.checked
        });
    }
    /** * click event *@param e
    * @returns {boolean}* /

    checkedToggle(e) {
        if (!this.props.disabled && this.props.onChange) {
            this.props.onChange(!this.props.checked); }}render() {
        return (
            <div className={this.getCheckboxWrapperClassName()}
            onClick={(e)= > this.checkedToggle(e)}>
                <span className="checkbox"></span>
                <span className="checkbox-text">{this.props.children}</span>
            </div>); }}export default CheckBox;
Copy the code

Checkboxgroup.js = checkboxGroup.js

import React from 'react';
import PropTypes from 'prop-types';
import CheckBox from './CheckBox.js';
// To ensure that test cases run, the utils module built into Webpack is not used
import utils from '.. /.. /js/common/utils/index.js';
import './CheckBox.scss';
/** * CheckBoxGroup CheckBoxGroup */
class CheckBoxGroup extends React.Component {
    // Check the input type
    static propTypes = {
        [{label: "option1 ", value: 1}, {label:" option2 ", value: 2, disabled: true}]
        options: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
        if (typeofpropValue[key] ! = ='object') {
            return new Error(`Invalid prop \`${propFullName}\` of type \`The ${typeof propValue[key]}\` supplied to \`${componentName}\`, expected \`object\``);
        }

        if(! propValue[key].hasOwnProperty('label')) {
            return new Error(` \ `${componentName}\ 'Prop parameter of the component \'${propFullName}\ 'missing attribute \' label\ ')}if(! propValue[key].hasOwnProperty('value')) {
            return new Error(` \ `${componentName}\ 'Prop parameter of the component \'${propFullName}\ 'missing attribute \' value\ ')
        }

        }).isRequired,
        // Select an array of options value
        value: PropTypes.array,
        True indicates that the check box group is unavailable. The check boxes in this group are all gray
        disabled: PropTypes.bool,

        /** * Any option in the group selects the callback function * when the state changes@param {Array} NewGroupValue Specifies the array of new selected options */

        onChange: PropTypes.func.isRequired,
            // Outermost element style
            className: PropTypes.oneOfType([
            PropTypes.string,
            PropTypes.array,
            PropTypes.objectOf(PropTypes.bool)
        ])
    }

    // Enter the default value
    static defaultProps = {
        disabled: false.value: []}constructor(props) {
        super(props);
        this.state = {
            options: this.getCheckboxGroupOptionList()
        };
    }

    /** * Get the data to be used by this component after the options resolution */ add some properties to the props */

    getCheckboxGroupOptionList(){
        let itemOptions = [];
        if (this.props.options && this.props.options instanceof Array) {
            let optionItem;
            for (let i = 0; i < this.props.options.length; i++) { optionItem = {... this.props.options[i]};if (typeof this.props.options[i].value === 'object' && this.props.value instanceof Array) {
                    optionItem.checked = false;
                    for (let j =0; j < this.props.value.length; j++) {
                        if (JSON.stringify(optionItem.value) === JSON.stringify(this.props.value[j])) {
                            optionItem.checked = true;
                            break; }}}else {
                    optionItem.checked = this.props.value.includes(optionItem.value); } itemOptions.push(optionItem); }}return itemOptions;
    }

    /** * Select the class * required by the outermost layer of the box group@returns {string}* /
    getCheckboxGroupClassName(){
        return utils.clasx(this.props.className, {
            'checkbox-group': true.'checkbox-group-disabled': this.props.disabled
        })
    }

    /** * click event *@param {number} Idx Current option index *@returns {boolean} NewChecked Indicates the newly checked status of the current option */
    itemToggle(idx, newChecked) {
        this.state.options[idx].checked = newChecked;
        let newGroupValue = [];
        for (let i = 0; i < this.state.options.length; i++) {
            let optionItem = this.state.options[i];
            if(optionItem.checked){ newGroupValue.push(optionItem.value); }}this.props.onChange(newGroupValue)
    }
    render() {
        return (
            <div className={this.getCheckboxGroupClassName()}>
                {this.state.options.map((item, index) =>
                    <CheckBox
                        key={JSON.stringify(item.value)}
                        checked={item.checked}
                        disabled={item.disabled || this.props.disabled}
                        onChange={(newChecked)= > this.itemToggle(index, newChecked)}>
                        {item.label}
                    </CheckBox>
                )}
            </div>); }}export default CheckBoxGroup;
Copy the code

“Feel free to discuss in the comments section.”

Hope to finish watching friends can give a thumbs-up, encourage once