【问题标题】:Using styles in react theme在反应主题中使用样式
【发布时间】:2019-11-02 05:22:26
【问题描述】:

我需要在以下代码中从 const 转换为 React 组件格式。但我做不到,即使我不得不尝试状态。以下是实际代码。

const LoginPage = () => {

const styles = {
    loginContainer: {
      minWidth: 320,
      maxWidth: 400,
      height: 'auto',
      position: 'absolute',
      top: '20%',
      left: 0,
      right: 0,
      margin: 'auto'
    },
  };

return (
    <MuiThemeProvider muiTheme={ThemeDefault}>
      <div>
        <div style={styles.loginContainer}>
         <h1>Testing</h1>
                   <Checkbox
                    label="Remember me"
                    style={styles.checkRemember.style}
                    labelStyle={styles.checkRemember.labelStyle}
                    iconStyle={styles.checkRemember.iconStyle}
                  />
        </div>
      </div>
    </MuiThemeProvider>
);

但是由于我有一些构造和交互性,所以我想从 const LoginPage 转换为 class LoginPage extends React.Component 但是当我使用样式时它会给我错误。

class LoginPage extends React.Component {

    constructor(props) {
      super(props);

      if(authenticationService.currentUserValue) {
        this.props.history.push('/');
      }

    }

>>  const styles = {
      loginContainer: {
        minWidth: 320
}
}

render() {
    return (
      <MuiThemeProvider muiTheme={ThemeDefault}>
        <div>
          <div style={styles.loginContainer}>
          <h1>Test</h1>
          </div>
        </div>
      </MuiThemeProvider>
     )
}
}

那么如何在我的 React.Component 结构中使用这些样式。

【问题讨论】:

  • 您想要的是样式化组件之类的东西。它们可以通过利用 react 组件进行样式设置来帮助您在组件内部进行样式设置。样式组件:styled-components.com
  • 是的,我想在我的 React 组件中使用相同的样式,因为 const 导出不允许构造函数。

标签: css reactjs components


【解决方案1】:

使用类外的样式

class LoginPage extends React.Component {

    constructor(props) {
      super(props);

      if(authenticationService.currentUserValue) {
        this.props.history.push('/');
      }

    }

render() {
    return (
      <MuiThemeProvider muiTheme={ThemeDefault}>
        <div>
          <div style={styles.loginContainer}>
          <h1>Test</h1>
          </div>
        </div>
      </MuiThemeProvider>
     )
}
}

const styles = {
      loginContainer: {
        minWidth: 320
}
}

【讨论】:

  • 美丽我看到很多地方我得到了不同的建议,我认为这行不通,但它确实有效。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-03-01
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多