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

问题描述 投票:1回答:1

[在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;
javascript reactjs static react-hooks
1个回答
1
投票

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

const staticProp = "Hello, World!";

const MyComponent = () => {
  return (
    <div>{staticProp}</div>
  )
}
© www.soinside.com 2019 - 2024. All rights reserved.