[在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;
Refs对于绑定到组件实例的mutable values很有用。它们类似于实例变量。如果该变量应该是静态的,则不需要引用。您可以将其声明为组件函数的属性,或者在外部范围中声明为常量:
const staticProp = "Hello, World!";
const MyComponent = () => {
return (
<div>{staticProp}</div>
)
}