programing

리액트 네이티브로 함수가 가득한 도우미 파일을 작성하려면 어떻게 해야 합니까?

easyjava 2023. 3. 10. 22:52
반응형

리액트 네이티브로 함수가 가득한 도우미 파일을 작성하려면 어떻게 해야 합니까?

비슷한 질문이 있는데 여러 기능을 가진 파일을 만들지 못하고 있습니다.RN은 매우 빠르게 진화하고 있기 때문에 이 방법이 이미 구식인지 아닌지는 확실하지 않습니다.리액트 네이티브에서 글로벌 도우미 기능을 만드는 방법

리액트 네이티브는 처음입니다.

재사용 가능한 함수가 많은 js파일을 생성하여 컴포넌트로 Import하여 호출합니다.

내가 지금까지 해온 일이 바보같이 보일 수도 있지만, 네가 요구할 것을 알고 있어. 그래서 그들이 여기 있어.

찬두라는 클래스 이름을 만들어서 이렇게 내보내려고 했어요.

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

그런 다음 필요한 컴포넌트로 Import합니다.

import Chandu from './chandu';

그리고 이렇게 부르면

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

동작하는 것은 첫 번째 console.log뿐입니다.즉, 올바른 경로를 Import하고 있지만 다른 경로는 Import하고 있지 않습니다.

어떻게 하면 좋을까요?

간단한 메모:클래스를 가져오고 있습니다. 정적 속성이 아니면 클래스의 속성을 호출할 수 없습니다.자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes 를 참조해 주세요.

하지만 쉬운 방법이 있어요.도우미 기능을 만드는 경우 대신 다음과 같이 함수를 내보내는 파일을 만들어야 합니다.

export function HelloChandu() {

}

export function HelloTester() {

}

그런 다음 다음과 같이 Import합니다.

import { HelloChandu } from './helpers'

아니면...

import functions from './helpers'그리고나서functions.HelloChandu

다른 방법으로는 함수가 객체의 속성인 const 객체가 있는 도우미 파일을 작성하는 방법이 있습니다.이렇게 하면 하나의 개체만 내보내고 가져올 수 있습니다.

helpers.delpers.delpers.delpers.

const helpers = {
    helper1: function(){

    },
    helper2: function(param1){

    },
    helper3: function(param1, param2){

    }
}

export default helpers;

다음으로 다음과 같이 Import합니다.

import helpers from './helpers';

다음과 같이 사용합니다.

helpers.helper1();
helpers.helper2('value1');
helpers.helper3('value1', 'value2');

이게 도움이 될 거라고 확신해요.디렉토리내의 임의의 장소에 fileA 를 작성해, 모든 기능을 export 합니다.

export const func1=()=>{
    // do stuff
}
export const func2=()=>{
    // do stuff 
}
export const func3=()=>{
    // do stuff 
}
export const func4=()=>{
    // do stuff 
}
export const func5=()=>{
    // do stuff 
}

여기에서는 React 컴포넌트 클래스에서 Import 스테이트먼트를 1개만 작성할 수 있습니다.

import React from 'react';
import {func1,func2,func3} from 'path_to_fileA';

class HtmlComponents extends React.Component {
    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }
    rippleClickFunction(){
        //do stuff. 
        // foo==bar
        func1(data);
        func2(data)
    }
   render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

원하는 것을 달성하고 파일을 통해 더 나은 조직을 만들기 위해 index.js를 생성하여 도우미 파일을 내보낼 수 있습니다.

를 들어 /helpers라는 폴더가 있다고 합시다.이 폴더 내에서는 내용, 동작 또는 마음에 드는 것별로 구분된 기능을 만들 수 있습니다.

예를 들어:

/* Utils.js */
/* This file contains functions you can use anywhere in your application */

function formatName(label) {
   // your logic
}

function formatDate(date) {
   // your logic
}

// Now you have to export each function you want
export {
   formatName,
   formatDate,
};

테이블 조작에 도움이 되는 기능을 가진 다른 파일을 만듭니다.

/* Table.js */
/* Table file contains functions to help you when working with tables */

function getColumnsFromData(data) {
   // your logic
}

function formatCell(data) {
   // your logic
}

// Export each function
export {
   getColumnsFromData,
   formatCell,
};

이제 helpers 폴더 안에 index.js를 두는 방법이 있습니다.

/* Index.js */
/* Inside this file you will import your other helper files */

// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';

// Export again
export {
   Utils,
   Table,
};

이제 각 기능을 사용하기 위해 개별적으로 가져올 수 있습니다.

import { Table, Utils } from 'helpers';

const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);

const myName = Utils.formatName(someNameVariable);

더 나은 방법으로 파일을 정리하는 데 도움이 되기를 바랍니다.

클래스를 사용하고 싶다면 이렇게 하면 됩니다.

Helper.js

  function x(){}

  function y(){}

  export default class Helper{

    static x(){ x(); }

    static y(){ y(); }

  }

App.js

import Helper from 'helper.js';

/****/

Helper.x

나는 그의 이름은 Utils이고 내부 페이지 인덱스를 만드는 것을 선호한다.

const findByAttr = (component,attr) => {
    const wrapper=component.find(`[data-test='${attr}']`);
    return wrapper;
}

const FUNCTION_NAME = (component,attr) => {
    const wrapper=component.find(`[data-test='${attr}']`);
    return wrapper;
}

export {findByAttr, FUNCTION_NAME}

기본 키워드 look을 사용하지 않았기 때문에 이것을 사용해야 할 경우 "{}"을(를) 사용하여 Import해야 합니다.

 import {FUNCTION_NAME,findByAttr} from'.whare file is store/utils/index'

Utils.js와 같은 이름의 파일을 만들고 모든 함수와 함께 내보내기를 사용합니다.

export function firstFunction(){
}

export function secondFunction(){
}

이제 이러한 기능을 가져오고 사용할 수 있는 두 가지 방법이 있습니다.

  1. 로서 그것들을 개별적으로 수입하다
import {firstFunction, secondFunction} from './Utils'

그리고 그것들을

firstFunction()
secondFunction()
  1. 로서 통칭하여 Import하다
import * as Utils from './Utils'

그리고 그것들을

Utils.firstFunction()
Utils.secondFunction()

언급URL : https://stackoverflow.com/questions/38402025/how-to-create-helper-file-full-of-functions-in-react-native

반응형