繁体   English   中英

是否可以使用 class 向 React 组件添加内联样式?

[英]Is it possible to add inline styling to a React component by using a class?

所以我是 React 的新手,我来自 Angular 背景,我们只有类。
我现在想弄清楚在使用 class 时是否可以为我的 html 添加样式。

React 文档(关于Drawers )使用 function 来创建组件。 但我习惯于使用类而不是函数。

所以问题是,是否可以按照我现在尝试的方式(以及在课堂上)为元素添加样式?

const useStyles = makeStyles({
    list: {
      width: 250,
    }
});

export default class NavBar extends Component<any, any> {

    constructor(props: any) {
        super(props);
        this.state = { open: false };
    }

    // Will complain about this
    readonly classes = useStyles();

    render() { 
        return (
            <div className={this.classes.list}>test</div>
        )
    }
}

错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。 这可能由于以下原因之一而发生:
1. React 和渲染器的版本可能不匹配(例如 React DOM)
2. 你可能违反了 Hooks 规则
3. 你可能在同一个应用程序中拥有多个 React 副本
有关如何调试和解决此问题的提示,请参阅...

这就是您如何使用样式 object 在 react 中定义内联样式的方法。

const useStyles = {
  list: {
    width: 250,
    color: 'red'
  }
};
class NavBar extends React.Component {
  constructor(props) {
      super(props);
      this.state = { open: false };
  }
  render() { 
      return (
          <div style={useStyles.list}>test</div>
      )
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM