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

时间:2019-09-30 22:31:08

标签: javascript reactjs static react-hooks

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 个答案:

答案 0 :(得分:2)

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

const staticProp = "Hello, World!";

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