【发布时间】:2017-12-24 14:58:21
【问题描述】:
我正在使用 React Native 制作应用程序。 最困难的部分是处理 javascript。我使用 Xamarin.Forms 制作了几个应用程序。现在我被 React Native 所吸引。
顺便说一句。
当我打电话时
console.log('I should be given B', B.getInstance())
在 App.js 文件中。
我不明白为什么我得到了 A 的实例而不是 B 的实例,即使我调用了 B 的静态方法。
谢谢。
[Root.js]
import App from './App'
import A from './A'
export default class Root extends React.Component{
render(){
return (
<View>
<App/>
<A/>
</View>
)
}
}
[App.js]
import A from './A'
import B from './B'
export default class App extends React.Component{
componentDidMount(){
console.log('I should be given B', B.getInstance())
//*************** BUT I get A's instance!!!!!!! ****************
}
render(){
return (
<View>
<A/>
<B/>
</View>
)
}
}
[A.js]
import React from 'react'
import { Text } from 'react-native';
export default class A extends React.Component{
static instance = null;
static getInstance(){
return A.constructor.instance;
}
title = 'I\'m A';
componentWillMount(){
A.constructor.instance = this;
}
render(){
return <Text>I'm A</Text>
}
}
[B.js]
import React from 'react'
import { Text } from 'react-native';
export default class B extends React.Component{
static instance = null;
static getInstance(){
return B.constructor.instance;
}
title = 'I\'m B';
componentWillMount(){
B.constructor.instance = this;
}
render(){
return <Text>I'm B</Text>
}
}
【问题讨论】:
-
你想用你的组件中的实例来完成什么?
-
这只是一个例子。我唯一的好奇是为什么我得到 A 的实例而不是 B 的实例。
-
我对 JavaScript 中的类还不太了解,但根据我有限的知识,构造函数是一种方法,而不是你应该放东西的垃圾对象。所以你需要的只是
return B.instance。其中 B.instance 实际上不是真正的静态类属性,因为 JavaScript 不支持它。而且您应该刚刚编辑了上一个问题,这不是一个不同的问题。 -
而且我不了解 React(最佳)实践,但使用 getInstance 对我来说意义不大。您可能应该在您的班级下方写
export default new B(),而不是导出您的班级。或者让一些全局类保留对实例的所有引用。 -
嗨@René 我同意我应该编辑我以前的问题,但是如果我把所有东西都放在那里,我担心它会很乱而且已经有了答案,所以我担心答案似乎是错误的,即使我的问题可能是错误的。无论如何,使用构造函数是在 javascript 中访问内部静态成员的正确方法。它可能看起来很奇怪,因为我也有同样的想法。
标签: javascript reactjs react-native