【问题标题】:How to use Hook API style [duplicate]如何使用 Hook API 风格 [重复]
【发布时间】:2020-02-14 08:14:47
【问题描述】:

我正在学习“如何设置材质 UI 组件的样式”。在本教程中,它为您提供了以下 Hook Api 代码:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles({
  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',
  },
});

export default function Hook() {
  const classes = useStyles();
  return <Button className={classes.root}>Hook</Button>;
}

据我了解,我有一个具有这种风格道具的新按钮。我的问题是如何在渲染中使用这个新按钮?

class CreateUserPage extends React.Component {
    render() {
        return (
            // How to use it???
        );    
    }
}

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    我的问题是如何在我的渲染中使用这个新按钮?

    您创建了一个名为 Hook 的组件。 (你应该把它改成ButtonStyledButton 之类的。

    export default function Hook() {
      const classes = useStyles();
      return <Button className={classes.root}>Hook</Button>;
    }
    

    要在 CreateUserPage 中使用它,您只需导入它并像普通 React 组件一样渲染它。

    import Hook from '../place/here/your/component/is'
    
    class CreateUserPage extends React.Component {
        render() {
            return (
                ...
                <Hook />
            );    
        }
    }
    

    【讨论】:

    • 我也可以像这样导出多个 Hook 函数吗?
    • @ErayTuncer 是的。它不叫Hook functions,而是Functional Components,它也是React Component。钩子函数是useStyles,只能在Functional Components中使用,不能与Class Components一起使用。
    【解决方案2】:

    此代码需要保存在专用 javascript 文件(例如NewButton.js)中,您现在可以其他组件导入该文件。

    import NewButton from './NewButton'
    
    <NewButton>Hi</NewButton>
    

    你需要调整你的钩子以传播它的内容

    export default function Hook({children}) {
      const classes = useStyles();
      return <Button className={classes.root}>{children}</Button>;
    }
    

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 2013-10-09
      • 2021-10-25
      • 2010-12-03
      • 1970-01-01
      • 2016-03-21
      • 1970-01-01
      • 2018-02-09
      相关资源
      最近更新 更多