FE — React

JSX #

className #

props #

组件无论是使用函数声明还是通过 class 声明,都决不能修改自身的 props。所有 React 组件都必须像纯函数一样保护它们的 props 不被更改。

建议从组件本身的角度来命名 props 而不是它被使用的上下文环境。

纯函数 #

  • 不会尝试更改入参,且多次调用下相同的入参始终返回相同的结果
  • 不会触发事件

state #

this.setState() #

Refs #

React.createRef 创建一个能够通过 ref 属性附加到 React 元素的 ref

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

默认情况下,你不能在函数组件上使用 ref 属性,因为它们没有实例,你可以在函数组件内部使用 ref 属性,只要它指向一个 DOM 元素或 class 组件:useRef(null);

理解:“函数组件没有实例”

context #

为了避免变量通过 props 层层传递,可以只在最顶层的组件中设置 context,然后所有的子组件都可以通过 this.context.xx 获取到。

// 初始化
const MyContext = React.createContext(defaultValue);

// 设置传递
<MyContext.Provider value={/* 某个值 */} />

// 使用
const {state, dispatch} = useContext(Context)

// 组件类中也可以通过 contextType 使用
MyClass.contextType = MyContext;

数据流 #

类似 Vue 的“双向数据流”在 react 里怎么实现的?

useState?

也可以通过 redux 实现。

Portals #

hook #

Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。

import React, { useState } from 'react';

function Example() {
  // 声明一个叫 “count” 的 state 变量。
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

命令行 #

create react app #

npm install -g create-react-app
npx create-react-app my-app --template typescript

babel #

react 需要 babel 来预编译 jsx 文件。

本文共 537 字,上次修改于 Oct 19, 2022
相关标签: 前端