javascript - 在 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 methods
with 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'
推荐阅读
- python - 返回所有参数总和的函数
- .htaccess - 暂停站点地图文件的尾部斜杠规则
- c# - 通过 C# 从市场映像中提升 Azure VM
- django - Django-tables2 为列标题指定 verbose_name 无效
- java - 使用应用程序属性文件在本机查询中选择表名?
- docker - FFmpeg 使用 -loop 标志的意外行为
- swift - Swift:将 SwiftUI 元素添加到 UIKit 项目:无法正确应用约束
- performance - System.Data.SQLite 版本 1.0.74 和最新的 1.0.113 之间有什么变化?
- excel - 如何在python中计数,并直接在数据框中创建列(与多列分组)
- python - 读取 CSV 文件并跳过一些值