React 跨组件共享方法

IT技术 javascript reactjs
2021-04-24 22:48:58

到目前为止,我有一个看起来像这样的组件:

import React from 'react';

// Import images
import logo from '../images/logo-small.png';

class LoginForm extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            email: '',
            password: '',
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(e) {
        const target = e.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    }

我将handleChange(e)在我的应用程序上的多个文件的多个组件中重复使用相同的方法。有没有办法可以分离出这个方法,而不必每次都重写它?

每次我需要使用它时,我会输入handleChange(e)文件名utils.js并导入该文件吗?如果是这样,我如何确保它this.setState正常工作?

我对如何解决这个问题有一些粗略的想法(例如上面的那个),但我想采取最好的方法来解决这个问题。谢谢!

4个回答

Hooks是另一种方式。

使用自定义钩子,您可以轻松地在组件之间重用状态相关处理程序。

// hooks.js
const { useState } from 'react';

const useHandleChange = () => {
  const [formValues, setFormValues] = useState({});

  const handleChange = (e) => {
    let { type, checked, name, value} = e.target;
    value = type === 'checkbox' ? checked : value;

    setFormValues({
      [name]: value
    });
  };

  return { formValues, handleChange };
}

// Component.js
import useHandleChange from './hooks';

const LoginForm = () => {
  // you can use that on each component that needs the handleChange function
  const { formValues, handleChange } = useHandleChange();

  return (
    // html template
  );
};

您需要将您的组件转换为函数 component,但因此只有在不需要太多努力来重构您的代码时,我才会提出此解决方案。Hooks 不适用于类组件。

当然。您正在寻找的是所谓的高阶组件

您可以使用需要共享的所有方法/逻辑创建一个 HOC,并用它包装您需要增强的组件。

您当然可以创建一个辅助函数。但是,setState()在保存状态的组件中包含的内容是很好的。

为此,您可以执行以下操作:

// utils.js helper function
handleCheckbox(e) {
  const target = e.target,
        value = target.type === 'checkbox' ? target.checked : target.value;
  return {name: target.name, value: value};
}


// In your component
handleChange(e) {
  // Destructured in case you need to handle it differently
  const { name, value } = handleCheckbox(e);
  this.setState({[name]: value});
}

助手可以通过{[name]: value},但它不一定要关心变量最终是如何使用的。

例如utils.js我想只需创建新文件并从中导出您的函数,如下所示

const handleChange = (e) => {
        const target = e.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        return { [name]: value }
}

export.handler = handleChange;

而不是将其导入到您的文件中,例如像这样:

const utils = require('path/to/file');

setState(utils.handleChange(e));

快乐编码!