React Hooks 静态变量:对象属性与 useRef() [英] React Hooks Static Variables: Object Property vs useRef()

查看:25
本文介绍了React Hooks 静态变量:对象属性与 useRef()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

useRef() 钩子中的 React 功能组件中声明静态变量与简单地将它们声明为对象属性相比,有哪些优点或缺点.

What are the advantages or disadvantages to declaring static variables in a React functional components within a useRef() hook vs. simply declaring them as an object property.

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 对于 可变值 绑定到您的组件实例.它们类似于实例变量.如果变量应该是静态的,则不需要引用.您可以将其声明为组件函数的属性,或者声明为外部作用域中的常量:

Refs are useful for mutable values bound to your component instances. They are similar to instance variables. If the variable is supposed to be static, you don't need refs. You can declare it as a property of your component function, or as a constant in the outer scope:

const staticProp = "Hello, World!";

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

这篇关于React Hooks 静态变量:对象属性与 useRef()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆