简体   繁体   English

如何在反应中使用 vue.js mixin?

[英]How do I use vue.js mixin in react?

On a daily basis I'm using vue.js but right now I'm working on a react project.我每天都在使用 vue.js 但现在我正在做一个反应项目。 I've got this translation method:我有这个翻译方法:

function __(key, replace = null) {
    let translation, translationNotFound = true;

    try {
        translation = key.split('.').reduce((t, i) => t[i] || null, window._translations[window._locale].php);

        if (translation) {
            translationNotFound = false;
        }
    } catch (e) {
        translation = key;
    }

    if (translationNotFound) {
        translation = window._translations[window._locale]['json'][key]
            ? window._translations[window._locale]['json'][key]
            : key;
    }

    if (replace) {
        replace.forEach((value, key) => {
            translation = translation.replace(':' + key, value);
        });
    }

    return translation;
}

In vue I'm using a mixin for this so it can be used everywhere.在 vue 中,我为此使用了一个 mixin,因此它可以在任何地方使用。 How can I make sure I can use this method in my react components?如何确保可以在我的反应组件中使用此方法?

Already red lots of articles online but can't figure it out.网上已经红了很多文章,但是搞不明白。

Just export your function只需导出您的 function

const myFunction = (key, replace = null) => {
    let translation, translationNotFound = true;

    try {
        translation = key.split('.').reduce((t, i) => t[i] || null, window._translations[window._locale].php);

        if (translation) {
            translationNotFound = false;
        }
    } catch (e) {
        translation = key;
    }

    if (translationNotFound) {
        translation = window._translations[window._locale]['json'][key]
            ? window._translations[window._locale]['json'][key]
            : key;
    }

    if (replace) {
        replace.forEach((value, key) => {
            translation = translation.replace(':' + key, value);
        });
    }

    return translation;
}

export default myFunction;

When you want to import当您要导入时

import myFunction from 'path/to/the/file'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM