首页 > 解决方案 > 在 Hooks React 中使用静态变量

问题描述

我如何使用静态变量React Hooks?我有一个组件,我想将它传递给钩子,但我有一个问题,因为static

旧例:

class MyComponent extends Component {
  static myComponentInstance

  static show({...config}){
    this.myComponentInstance.start(config)
  }

  start({...config}){ // my code function here }
}

新版本

const MyComponent = (props) => {
  const myComponentInstance = useRef(null)

  const start = ({...config}){ // my code function here }
}

看了一点useRef,不知道用对不对,怎么做我的show方法static

这样做,我可以从另一个组件调用我的组件的方法(它已经与类一起使用)

前任:

import { Root, myComponent } from 'myComponent'

<Root>
  <a onclick="myComponent.show({...})">Show</a>
</Root>

是否可以使用 static methodswith react hooks

标签: javascriptreactjsreact-native

解决方案


您不能使用static,但属性和变量仍然存在

虽然@Clarity 是正确的,您不能将静态方法/属性与基于函数的 React 组件一起使用,但出于您的意图和目的,静态方法/属性等同于函数/变量。

一方面,您可以简单地将方法和属性附加到您的MyComponent喜欢上:

MyComponent.myComponentInstance = null
MyComponent.show = function() {}
// Using function keyword allows you to use the `this` keyword to reference MyComponent

除了 OOP,还有其他选择

另一种选择是简单地创建变量/函数并导出它们。这将像导出组件一样利用模块系统。

export let myComponentInstance
export function show () {}

然后,要使用它们,您可以导入它们:

import { myComponentInstance, show } from './example.js'

推荐阅读