如何在 React Native 中创建充满功能的帮助文件?

编程入门 行业动态 更新时间:2024-10-07 20:30:27
本文介绍了如何在 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?

推荐答案

快速说明:您正在导入一个类,除非它们是静态属性,否则不能调用类上的属性.在此处阅读有关类的更多信息:developer.mozilla/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: developer.mozilla/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 中创建充满功能的帮助文件?

本文发布于:2023-11-27 21:29:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639673.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:帮助文件   功能   如何在   Native   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!