programing

ReactJs 글로벌 도우미 기능

lastmemo 2023. 3. 17. 19:33
반응형

ReactJs 글로벌 도우미 기능

문제: 컴포넌트에 상주할 필요가 없는 작은 도우미 기능이 많이 있습니다(또는 컴포넌트가 많은 코드로 인해 비대해질 수 있습니다.저의 게으름뱅이는 이 모든 것을 컴포넌트가 호출할 수 있는 글로벌 기능이라고 생각하고 있습니다.정말 좋은 ReactJs 코드를 만들고 싶어요.

질문:.Reactjs의 글로벌 도우미 기능에 관한 베스트 프랙티스는 무엇입니까?어떤 컴포넌트에 강제로 넣어야 할까요, 아니면 다른 컴포넌트에 밀어 넣어야 할까요?

기본적인 예:

function helperfunction1(a, b) {
    //does some work
    return someValue;
}

function helperfunction2(c, d) {
    //does some work
    return someOtherValue;
}

function helperfunction3(e, f) {
    //does some work
    return anotherValue;
}

function helperfunction4(a, c) {
    //does some work
    return someValueAgain;
}


var SomeComponent =
    React.createClass({

        //Has bunch of methods

        //Uses some helper functions

        render: function () {

        }

    });

var SomeOtherComponent =
    React.createClass({

        //Has bunch of methods

        //Uses some helper functions

        render: function () {

        }

    });

하나의 파일에서 여러 함수를 내보낼 수 있으며 반응 자체는 필요하지 않습니다.

Helpers.js:

export function plus(a, b) {
  return a + b;
}

export function minus(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  return a / b;
}

그런 다음 필요한 기능을 가져올 수 있습니다.

import { multiply, divide } from './Helpers'

이를 위해 Webpack이나 Browserify 의 모듈 번들 도구를 사용할 수 있습니다.재사용 가능한 기능을 공통에 포함JS 모듈

Mixins는 사용하지 마십시오.아마도 다음 버전의 React에서는 권장되지 않을 것입니다.ES6 구문을 사용한 React에서는 mixin을 선언하는 표준 방법이 없고 mixin을 표준화하는 ES7을 기다리는 것을 선호하기 때문입니다.또한 React 라이프사이클의 방법을 사용하지 않는 한 재사용 가능한 코드를 React와 결합하는 것은 의미가 없습니다.

modulejs를 사용할 수 있습니다.또는 mixin(https://facebook.github.io/react/docs/reusable-components.html#mixins))을 사용할 수 있습니다.

믹스인 샘플: https://jsfiddle.net/q88yzups/1/

var MyCommonFunc = {
    helperFunction1: function() {
       alert('herper function1');
    },
    doSomething: function(){
        alert('dosomething');
    }
}

var Hello = React.createClass({
    mixins: [MyCommonFunc],
    render: function() {
        this.doSomething();
        return <div onClick={this.helperFunction1}>Hello {this.props.name} </div>;
    }
});

React.render(<Hello name="World" />, document.getElementById('container'));

다른 옵션으로, 별도의 모듈로 분할하고 싶지 않은 경우 다음과 같이 부모 컴포넌트에 전용 메서드를 생성하여 이 컴포넌트 내에서 자유롭게 사용하거나 소품을 통해 자녀 컴포넌트에 전달할 수 있습니다.

var YourComponent = React.createClass({

    globalConfig: function() {
        return {
            testFunc: function () {
                console.log('testing...');
            },
        };
    }(),

    ......
    render: function() {
        this.globalConfig.testFunc(); // use directly

        <ChildComponent testFunc={this.globalConfig.testFunc} /> // pass to child
    .....

모두 검증되지 않았지만 그게 아이디어야

리액트 컨텍스트를 사용하여 다음과 같은 작업을 수행합니다.이 제품은 이 사용 사례에 맞게 제작되었습니다.문서: https://reactjs.org/docs/context.html

Michiel이 말한 것처럼 리액션은 모두 회피할 수 있습니다.단, 약간의 개선은 모든 순수한 js 함수를 하나의 플립에 넣고 그것을 당신의 html 시작 페이지에 연결하면 그 함수는 어디에서나 사용할 수 있습니다.

한 사람만 가지고

<script src='./global-func.js' ></script>

지저분한 해킹이지만 효과가 있다;)

작성하는 모든 컴포넌트 클래스로 파일을 Import할 필요가 없습니다.

언급URL : https://stackoverflow.com/questions/30205145/reactjs-global-helper-functions

반응형