Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

reactjs - How to create helper file full of functions in 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?

I am new to React Native.

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.

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';

And then call it like this

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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() {

}

Then import them like so:

import { HelloChandu } from './helpers'

or...

import functions from './helpers' then functions.HelloChandu


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...