React知识点总结(二)

React知识点总结(二)

一、为什么列表循环渲染的key最好不要用index?

举例:
变化前数组的值是[1,2,3,4],key就是对应的下标:0,1,2,3 变化后数组的值是[4,3,2,1],key对应的下标也是:0,1,2,3

由于key相同而值不同会进行删除和添加操作,但是原本可以进行移动操作的,显然删除和添加操作更消耗性能。

二、什么是上下文Context?

Context 提供了一个无需为每层组件手动添加 props,就能在组件树间进行数据传递的方法。

// Context 可以让我们无须明确地传遍每一个组件,就能将值深入传递进组件树。
// 为当前的 theme 创建一个 context(“light”为默认值)。
const ThemeContext = React.createContext('light');
class App extends React.Component {
    
    
  render() {
    
    
    // 使用一个 Provider 来将当前的 theme 传递给以下的组件树。
    // 无论多深,任何组件都能读取这个值。
    // 在这个例子中,我们将 “dark” 作为当前的值传递下去。
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// 中间的组件再也不必指明往下传递 theme 了。
function Toolbar() {
    
    
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
    
    
  // 指定 contextType 读取当前的 theme context。
  // React 会往上找到最近的 theme Provider,然后使用它的值。
  // 在这个例子中,当前的 theme 值为 “dark”。
  static contextType = ThemeContext;
  render() {
    
    
    return <Button theme={
    
    this.context} />;
  }
}

1.创建createContext对象

2.用Context.Provider包裹要获取值的组件

3.在组件中设置static contextType = ThemeContext;就可以使用this.context访问

三、受控组件与非受控组件

1.受控组件

  • 渲染组件的唯一数据源是组件中的State
  • 该组件还负责数据变动时需要的执行的操作

<input><textarea><select>都有一个value属性,用来设置当前值。

2.非受控组件

表单数据将交由 DOM 节点来处理,可用ref来获取表单元素的值。

四、React Portal

Portal ==> “传送门”。提供了一种将子节点渲染到存在于父组件以外的 DOM 节点的优秀的方案。
用途:如做Dialog对话框,想让对话框居中,但在固定位置写对话框组件容易受父级组件CSS样式,因此可以通过Portal将对话框组件送到指定位置。

使用:

import React from 'react';
import {
    
    createPortal} from 'react-dom';

class Dialog extends React.Component {
    
    
  constructor() {
    
    
    super(...arguments);

    const doc = window.document;
    this.node = doc.createElement('div');
    doc.body.appendChild(this.node);
  }

  render() {
    
    
    return createPortal(
      <div class="dialog">
        {
    
    this.props.children}
      </div>, //塞进传送门的JSX
      this.node //传送门的另一端DOM node
    );
  }

  componentWillUnmount() {
    
    
    window.document.body.removeChild(this.node);
  }
}

猜你喜欢

转载自blog.csdn.net/wdhxs/article/details/110846172