如何在 React Native 中创建充满功能的帮助文件? [英] How to create helper file full of functions in react native?

查看:31
本文介绍了如何在 React Native 中创建充满功能的帮助文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然有一个类似的问题,但我无法创建具有多个功能的文件.不确定该方法是否已经过时,因为 RN 发展非常快.如何在 React Native 中创建全局辅助函数?

Though there is a similar question I am failing to create a file with multiple functions. Not sure if the method is already outdated or not as RN is evolving very fast. How to create global helper function in react native?

我是 React Native 的新手.

I am new to React Native.

我想要做的是创建一个包含许多可重用函数的js文件,然后将其导入到组件中并从那里调用.

What I want to do is to create a js file full of many reusable functions and then import it in components and call it from there.

到目前为止我所做的可能看起来很愚蠢,但我知道你会要求它,所以它们在这里.

What I have been doing so far might look stupid but I know you will ask for it so here they are.

我尝试创建一个类名 Chandu 并像这样导出它

I tried creating a class name Chandu and export it like this

'use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  Text,
  TextInput,
  View
} from 'react-native';


export default class Chandu extends Component {

  constructor(props){
    super(props);
    this.papoy = {
      a : 'aaa'
    },
    this.helloBandu = function(){
      console.log('Hello Bandu');
    },
  }

  helloChandu(){
    console.log('Hello Chandu');
  }
}

然后我将它导入到任何需要的组件中.

And then I import it in any required Component.

import Chandu from './chandu';

然后这样称呼它

console.log(Chandu);
console.log(Chandu.helloChandu);
console.log(Chandu.helloBandu);
console.log(Chandu.papoy);

唯一有效的是第一个 console.log,这意味着我正在导入正确的路径,而不是任何其他路径.

The only thing that worked was the first console.log, which means that I'm importing the correct path, but not any others.

请问正确的做法是什么?

What is the correct way to do this please?

推荐答案

快速说明:您正在导入一个类,除非它们是静态属性,否则不能调用类上的属性.在此处阅读有关类的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

不过,有一种简单的方法可以做到这一点.如果您正在制作辅助函数,您应该制作一个导出函数的文件,如下所示:

There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:

export function HelloChandu() {

}

export function HelloTester() {

}

然后像这样导入它们:

import { HelloChandu } from './helpers'

或...

从'./helpers'导入函数然后functions.HelloChandu

这篇关于如何在 React Native 中创建充满功能的帮助文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆