前端小知识10点(2020.5.17)

324 阅读3分钟
1、Object.hasOwnProperty(a)和Object.a的区别
  let obj={a:1,b:2,}

  Object.prototype.c=3
  //常用方法会去找原型链上的属性/方法,即Object.prototype上刚刚自定义的属性c
  if(obj.c){ console.log('hasC')  } //hasC
  //但是使用hasOwnProperty()的话,是不会去找原型链上定义的key的
  if(obj.hasOwnProperty('c')){ console.log('hasOwnProperty') } //不会打印

obj. hasOwnProperty不会去找Object上原型链的属性,
obj.c会去找Object上原型链的属性

2、JS 浮点数,利用或运算`| 0`取整

React源码时,看到这一行:

return MAGIC_NUMBER_OFFSET - ((ms / UNIT_SIZE) | 0);

| 0是取整的意思:

console.log(19 / 3 | 0); //6

原理:
JS是用双精度浮点数来存储number类型的, 而|是二进制或,会先将number转为整数,再进行位运算,所以可以用来取整

补充:
(1) 关于或运算|具体的演算过程,请看:前端小知识10点(2020.3.20)中的「2、JS 中的 | 是什么意思?

(2) 非位运算符~是将数字转为负数再减一

~12  //-13
~-9  //8
3、Array.reduce()的参数含义
[01234].reduce(function(all, item, indexarray){
  return all + item;
}
);

all表示 item 前的元素总和
item表示当前执行的元素,注意:从 index=1开始
index表示当前位置,注意:从 1 开始
array表示当前操作的 array

参考:developer.mozilla.org/zh-CN/docs/…

4、dom转image原理简述

www.tuicool.com/articles/YZ…

5、React.createRef和React.useRef的区别

App每次渲染时,createRef会返回新的引用,useRef会返回相同的引用

6、如何在 React 中直接渲染 canvas ?

Error: Objects are not valid as a React child (found: [object HTMLCanvasElement]). If you meant to render a collection of children, use an array instead.

在 React 中直接渲染 canvas 会报错:

  import html2canvas from 'html2canvas';

  const [canvasOne, setCanvasOne] = useState(undefined);

  html2canvas(element)
    .then(function(canvas{
        setCanvasOne(canvas)
    });

<div>
  {canvasOne}
</div>

解决方法:

  import html2canvas from 'html2canvas';

  const [canvasOne, setCanvasOne] = useState(undefined);

  html2canvas(element)
    .then(function(canvas{
        setCanvasOne(canvas.toDataURL())
    });

<img src={canvasOne} />
7、使用原生js拖拽div的小demo

请看:www.jq22.com/webqd1348

8、给while循环命名,以便和内部的while循环区分开
  let a=5

  while1:while(a>0){
    a=a-1
    console.log(a,'while1')

    while(a>=3){
      console.log(a,'innerWhile2')
      //跳过本次循环,继续执行循环 while1
      continue while1
    }
    while(a<3){
      console.log(a,'innerWhile1')
      //跳过本次循环,继续执行循环 while1
      continue while1
    }

  }
9、将网页颜色置为灰色

使用 CSS3 的滤镜:

{
  filtergrayscale(100%);
}

详细请看:www.runoob.com/cssref/css3…

10、React实现双向数据绑定

React 是没有双向绑定的概念的,但实现也简单

view—>model,使用onChange更改state,也就是用户输入 input 的时候,改变了 state
model—>view,使用state更改value,也就是 state 更改的时候,改变了 input 的 value

import React, {useEffect, useState} from 'react';

export default function App({
  const [textValue, setTextValue] = useState('')

  return (
    <div>
      <input
        type="text"
        onChange={(e) =>
 {
          setTextValue(e.target.value)
        }}
        value={textValue}
      />
    </div>
  );
}

(完)