gpt4 book ai didi

reactjs - 如何使用 makeStyles 设置组件样式,同时在 Material UI 中仍然具有生命周期方法?

转载 作者:行者123 更新时间:2023-12-03 12:54:21 26 4
gpt4 key购买 nike

每当我尝试将 makeStyles() 与具有生命周期方法的组件一起使用时,我都会收到以下错误:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

下面是产生此错误的代码的一个小示例。其他示例也将类分配给子项。我在 MUI 文档中找不到任何显示使用 makeStyles 的其他方法并能够使用生命周期方法的内容。

    import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
root: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
}));

const classes = useStyles();

class Welcome extends Component {
render() {
if (this.props.auth.isAuthenticated()) {
return <Redirect to="/" />;
}
return (
<Container maxWidth={false} className={classes.root}>
<LogoButtonCard
buttonText="Enter"
headerText="Welcome to PlatformX"
buttonAction={this.props.auth.login}
/>
</Container>
);
}
}

export default Welcome;

最佳答案

嗨,您应该使用提到的高阶组件 API,而不是使用钩子(Hook) API here

我将修改文档中的示例以满足您对类组件的需求

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
root: {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
border: 0,
borderRadius: 3,
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
color: 'white',
height: 48,
padding: '0 30px',
},
});

class HigherOrderComponentUsageExample extends React.Component {

render(){
const { classes } = this.props;
return (
<Button className={classes.root}>This component is passed to an HOC</Button>
);
}
}

HigherOrderComponentUsageExample.propTypes = {
classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponentUsageExample);

关于reactjs - 如何使用 makeStyles 设置组件样式,同时在 Material UI 中仍然具有生命周期方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56432167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com