React Hooks 静态变量:对象属性与 useRef()

IT技术 javascript reactjs static react-hooks
2021-05-13 08:41:32

useRef()钩子内的 React 功能组件中声明静态变量与简单地将它们声明为对象属性有什么优点或缺点

useRef 方法:

import React, { useRef } from "react";

const MyComponent = () => {

  const staticProp = useRef("Hello, World!");

  return (
    <div>{staticProp.current}</div>
  )
}

export default MyComponent;

对象属性方法:

import React from "react";

const MyComponent = () => {

  return (
    <div>{MyComponent.staticPro}</div>
  )
}

MyComponent.staticProp = "Hello, World!";

export default MyComponent;
1个回答

Refs 对于绑定到组件实例的可变值很有用它们类似于实例变量。如果变量应该是静态的,则不需要引用。您可以将其声明为组件函数的属性,或作为外部作用域中的常量:

const staticProp = "Hello, World!";

const MyComponent = () => {
  return (
    <div>{staticProp}</div>
  )
}