javascript - 在 Hooks React 中使用静态变量

标签 javascript reactjs react-native

如何在 React Hooks 中使用静态变量? 我有一个组件,我想将它传递给钩子(Hook),但由于 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 方法静态

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

例如:

import { Root, myComponent } from 'myComponent'

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

是否可以将静态方法react hooks一起使用?

最佳答案

您不能使用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'

关于javascript - 在 Hooks React 中使用静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58068910/

相关文章:

javascript - JavaScript 中的实时文本颜色变化

reactjs - 如何修复使用 create-react-app 构建后的白屏?

android - 找不到参数 React Native Maps 的方法 implementation()

javascript - 尝试使用 React Hooks 时出现 "TypeError: Object(...) is not a function"错误(alpha)

javascript - 我们可以从一个无状态组件传递多个 props 并将其作为 react 中另一个无状态组件中的单个参数吗?

javascript - GetHTTPSttaus 代码获取 API——React Native

javascript - 更改 javascript 缩略图的 alpha 级别

javascript - 将我的 html 元素动画化为不同的背景颜色。

javascript - 在 XPage 中使用远程服务 (RPC)

reactjs - 基本 React 应用程序无法编译 - 解析错误