如何在 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/