最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Hooks Static Variables: Object Property vs useRef() - Stack Overflow

programmeradmin1浏览0评论

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

useRef Approach:

import React, { useRef } from "react";

const MyComponent = () => {

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

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

export default MyComponent;

Object Property Approach:

import React from "react";

const MyComponent = () => {

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

MyComponent.staticProp = "Hello, World!";

export default MyComponent;

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

useRef Approach:

import React, { useRef } from "react";

const MyComponent = () => {

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

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

export default MyComponent;

Object Property Approach:

import React from "react";

const MyComponent = () => {

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

MyComponent.staticProp = "Hello, World!";

export default MyComponent;
Share Improve this question asked Sep 30, 2019 at 22:31 Chunky ChunkChunky Chunk 17.2k17 gold badges91 silver badges165 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

Refs are useful for mutable values bound to your ponent 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 ponent function, or as a constant in the outer scope:

const staticProp = "Hello, World!";

const MyComponent = () => {
  return (
    <div>{staticProp}</div>
  )
}
发布评论

评论列表(0)

  1. 暂无评论