小编mit*_*514的帖子

从 React hook 返回 JSX 元素是不好的做法吗?

我为警报框编写了以下钩子:

import MuiAlert from '@material-ui/lab/Alert';
import { Snackbar } from '@material-ui/core';
import React from 'react';

export const useAlert = () => {
    const [open, setOpen] = React.useState(false);
    const [message, setMessage] = React.useState('');

    const openAlert = (message) => {
        setOpen(true);
        setMessage(message);
    };

    const closeAlert = (event, reason) => {    
        setOpen(false);
    };

    return {
        openAlert,
        Alert: <Snackbar open={open} onClose={closeAlert}><MuiAlert onClose={closeAlert}>{ message }</MuiAlert></Snackbar>
    };
};
Run Code Online (Sandbox Code Playgroud)

我将此钩子集成到其他功能组件中,如下所示:

import { useAlert } from './useAlert';

const Dashboard = () => {
    const { openAlert, Alert } …
Run Code Online (Sandbox Code Playgroud)

javascript jsx reactjs react-hooks react-functional-component

16
推荐指数
1
解决办法
1万
查看次数

React跨组件共享方法

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

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
        });
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

javascript reactjs

5
推荐指数
2
解决办法
5691
查看次数