Details in a React project

Table of contents

1. The specific use of && and ||

2. Nested use of ternary operators

3. Handling of empty arrays and empty objects

4. The use of activeKey

5. Restrict Chinese character input in Form form

6. Spaces cannot be entered before and after the Form form

7. Floating-point numbers cannot be entered before and after the Form form

8. Select the tabs in antd to remove the underline.

9. Capitalize the first letter

10. Only letters, numbers and -_ combinations are supported, and must start and end with an alphanumeric


1. The specific use of && and ||

      In the most basic syntax, && and || are very easy to understand.

      || true false return true
      && true false return false

      && is false when you see false, and || is true as long as there is one true, and it is false only when they are all false

      At the beginning of learning, the value thought of the scene of comparing two values, and did not pay attention to the judgment between multiple sets of data. For example, the following situation.

{
value.enable && 
value.cpu_or_memory && 
value.cpu_or_memory.length > 0 && 
value.cpu_or_memory.map((item, index) =>{
    return <span key={index}>
            {item}
            </span>
})
}

      In this small component packaged by myself, multiple judgments are used. First, it will judge whether the value is null or undefined. If the && sign is false, the following code will not be executed. If it is true, it will continue to execute. When all conditions are met The final code will be executed only when it is met, and it is usually used for loading state or empty state processing.

2. Nested use of ternary operators

 {
    item.MetricTargetType === "utilization" ? (
        <>
            {item.MetricsName === "cpu" ? ('cpu使用率') : ('内存使用率')}
        </>
    ):(
        <>
            {item.MetricsName === "cpu" ? ('cpu使用量') : ('内存使用量')}
        </>
    )
  }

      Taking this example as an example, there is a requirement that there are four situations. According to the different attribute values ​​returned by the backend, to judge different states, the nesting of ternary operators can be used here. It is worth noting that there needs to be a root node in react, so you need to add <></>, otherwise you will report crazy errors.

3. Handling of empty arrays and empty objects

      When using && and || to make judgments, the conversion results of empty arrays and empty objects are both true, but there is no corresponding data in the array or object. Think about it one more layer, if the specific data is not empty Value processing, then probably will report undefined error, affecting the normal operation of the program. Therefore, further judgment is required for empty arrays and empty objects.

        const arr = [] ;
        const obj = {} ;
        
        arr && console.log(arr,"这是一层判断的空数组");
        obj && console.log(obj,"这是一层判断的空对象");
        // 即使加了判断,仍会执行,在js中空对象与空数组在转化时都会判断成true

        
        arr && arr.length > 0 && console.log("这是两层判断的数组");
        obj && Object.keys(obj).length > 0 && console.log("这是两层判断的数组");
        // arr.length 是针对于数组取长度而设计的,因此空数组的长度为0 我们只需要判断其长度大于不大于0即可
        // Object.keys是针对对象取其键名的方法,取出后放在同一个数组里再去判断这个数组的长度是否大于零

        // 使用以上方法多重判断即可实现对于空数组空对象的过滤

4. The use of activeKey

      In the tabs component of Andt, there is an activeKey attribute used to replace the problem that the defaultActiveKey setting will not take effect, but I searched the Internet and found no related articles to introduce the use of activeKey.

        Add an onChange event to the imported component, and set activeKey to the value in state.

         Finally, use the onChange event to manipulate the click function to change the corresponding index value to achieve the switching effect.

5. Restrict Chinese character input in Form form

Key regex: /^[^\u4e00-\u9fa5]+$/g

                rules: [
                  {
                    required: true,
                    message: '请输入镜像仓库地址',
                    max: 255,
                  },
                  {
                    message: '不能输入汉字',
                    validator: this.validateNoChinese
                  }
                ],
  //不能输入非汉字效验  效验不能输入非空字符串
  validateNoChinese = (rule, value, callback) => {
    let reg = /^[^\u4e00-\u9fa5]+$/g;
    let regEmpty = /^\s*$/g;
    if (value && !reg.test(value)) {
      callback('书写格式错误');
    } else if (value && regEmpty.test(value)) {
      callback('缺陷编号不能为空');
    } else {
      callback();
    }
  }

6. Spaces cannot be entered before and after the Form form

Key regularity: /(^\s*)|(\s*$)/g

<FormItem {...formItemLayout} label="镜像仓库地址">
              {getFieldDecorator('domain', {
                initialValue: '',
                rules: [
                  {
                    required: true,
                    message: '请输入镜像仓库地址',
                    max: 255,
                  },
                  {
                    message: '不能输入汉字',
                    validator: this.validateNoChinese
                  }
                ],
                getValueFromEvent: event => {return event.target.value.replace(/(^\s*)|(\s*$)/g, '');},
              })(<Input placeholder="请输入镜像仓库地址" />)}
            </FormItem>

7. Floating-point numbers cannot be entered before and after the Form form

Key regex: /\D/g

  handleCheckPort = (rule, value, callback) => {
    const { getFieldValue } = this.props.form;
    const float = /\D/g;
    if (value < 1) {
      callback('请输入正整数');
      return;
    } else if (value.match(float)) {
      callback('禁止输入小数点');
    }
    callback();
  };

8. Select the tabs in antd to remove the underline.

 :global {
    .ant-tabs-bar {
      border-bottom: 0;
       //去除下边框
      .ant-tabs-ink-bar {
        visibility: hidden;
        //去除选中下划线
      }
    }
  }

9. Capitalize the first letter

   titleCase = (str) => {
    str = str.toLowerCase();
    var attr = str.split(" ");
    for(var i =0;i<attr.length;i++){
       attr[i]=attr[i].substring(0,1).toUpperCase() + attr[i].substring(1);
    }
    return attr.join(" ");
  }

10. Only letters, numbers and -_ combinations are supported, and must start and end with an alphanumeric

/^[a-zA-Z0-9]([-a-zA-Z0-9_]*[a-zA-Z0-9])?$/

Guess you like

Origin blog.csdn.net/qq_45799465/article/details/125804206