[英]Calling javascript function from react native component
Actually I am new to react native, I am calling a javascript function which is in singleton class.实际上,我是本机反应的新手,我正在调用单例类中的 javascript 函数。 I want to call this function from another react native component from constructor.But if I try to call, it is not calling that function.我想从构造函数的另一个反应本机组件调用此函数。但是如果我尝试调用,它不会调用该函数。
Code:代码:
export default class CustomScreen extends React.Component {
constructor(){
LoginUtil.getInstance().getLoginToken() // ==> not working
}
}
export default class LoginUtil {
static instance = null;
static createInstance() {
var object = new LoginUtil();
return object;
}
static getInstance () {
if (!LoginUtil.instance) {
LoginUtil.instance = LoginUtil.createInstance();
}
return LoginUtil.instance;
}
getLoginToken(){
return "token"
}
}
The way singleton pattern is done in JavaScript is by leveraging exports JavaScript 中单例模式的实现方式是利用导出
Like this:像这样:
// LoginUtils.js
class LoginUtil {
constructor() {
// Only called once
this.token = 'initial';
}
setLoginToken(token) {
this.token = token;
}
getLoginToken(){
return this.token;
}
}
export default new LoginUtil();
The trick is while exporting the instance, it will handle single instance and avoid writing boilerplate code for instantiating.诀窍是在导出实例时,它将处理单个实例并避免编写用于实例化的样板代码。
Then in your component file do as follow:然后在您的组件文件中执行以下操作:
import loginUtils from './LoginUtils';
export default class CustomScreen extends React.Component {
constructor(){
const token = loginUtils.getLoginToken()
}
}
EDIT:编辑:
The reason your may not work is because you need to add super()
in your component constructor as first statement:您可能无法工作的原因是因为您需要在组件构造函数中添加super()
作为第一条语句:
class CustomScreen extends React.Component {
constructor(){
super();
LoginUtil.getInstance().getLoginToken();
}
...
}
class CustomScreen extends React.Component { constructor(){ super() this.state = { token: LoginUtil.getInstance().getLoginToken() }; } render() { return <p>Token: {this.state.token}</p> } } class LoginUtil { static instance = null; static createInstance() { var object = new LoginUtil(); return object; } static getInstance () { if (!LoginUtil.instance) { LoginUtil.instance = LoginUtil.createInstance(); } return LoginUtil.instance; } getLoginToken(){ return "token-test" } } ReactDOM.render(<CustomScreen />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
Instead of exporting class from the singleton file, export its object like:不是从单例文件中导出类,而是像这样导出它的对象:
export default new LoginUtil()
Then import this object and call any function of that class然后导入这个对象并调用该类的任何函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.