Skip to content

React中使用 wm-tools-utils 工具函数库

步骤 1:安装工具函数库

首先,确保您已经在项目中安装了 wm-tools-utils

bash
npm install wm-tools-utils

或者

bash
yarn add wm-tools-utils

步骤 2:创建一个工具模块

在您的项目中,创建一个新的文件,例如 utils.js,并在其中导入 wm-tools-utils

javascript
// src/utils.js
const wmUtils = require('wm-tools-utils/dist/wanmo-utils.js');

const Utils = {
    ...wmUtils,
};

export default Utils;

步骤 3:在您的 React 组件中全局使用工具函数

现在,您可以在任何组件中导入 utils.js 模块,并使用其中的工具函数。例如:

javascript
// src/components/StringTrimExample.js
import React from 'react';
import Utils from '../utils';

const StringTrimExample = () => {
    const rawString = "  Hello, World!  ";
    const trimmedString = Utils.trimString(rawString, 'both');

    return (
        <div>
            <h1>字符串处理示例</h1>
            <p>原始字符串: "{rawString}"</p>
            <p>处理后的字符串: "{trimmedString}"</p>
        </div>
    );
};

export default StringTrimExample;

示例 2:在其他组件中使用

您可以在其他组件中以相同的方式使用 Utils

javascript
// src/components/ArrayUniqueExample.js
import React from 'react';
import Utils from '../utils';

const ArrayUniqueExample = () => {
    const numbers = [1, 2, 2, 3, 4, 4, 5];
    const uniqueNumbers = Utils.uniqueArray(numbers);

    return (
        <div>
            <h1>数组去重示例</h1>
            <p>原始数组: {JSON.stringify(numbers)}</p>
            <p>去重后的数组: {JSON.stringify(uniqueNumbers)}</p>
        </div>
    );
};

export default ArrayUniqueExample;

步骤 4:在主应用中使用

您可以在主应用文件中使用这些组件:

javascript
// src/App.js
import React from 'react';
import StringTrimExample from './components/StringTrimExample';
import ArrayUniqueExample from './components/ArrayUniqueExample';

const App = () => {
    return (
        <div>
            <h1>全局使用 wm-tools-utils 示例</h1>
            <StringTrimExample />
            <ArrayUniqueExample />
        </div>
    );
};

export default App;

步骤 5:渲染应用

确保在您的 index.js 中渲染 App 组件:

javascript
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(<App />, document.getElementById('root'));

结论

通过这种方式,您可以在整个 React 应用中轻松地访问 wm-tools-utils 中的工具函数。只需在任何组件中导入 utils.js,即可使用您需要的功能,而无需在每个组件中单独导入 wm-tools-utils。这样可以保持代码的整洁和一致性。