在 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,但我不知道使用它是否正确,以及我将如何使我的表演方法static

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

前任:

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

是否可以将静态methodsreact 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'

你根本不能在类组件中使用 React Hooks,这意味着static也不能与钩子一起使用。

更多信息在钩子规则中。

最新更新