【问题标题】:Apply CSS to particular component in ReactJS将 CSS 应用于 ReactJS 中的特定组件
【发布时间】:2021-01-13 11:15:53
【问题描述】:

我正在尝试使用包含我创建的网页的 react 创建个人投资组合。我将这些网页称为父容器中的组件。但问题是每个网页都有一些冲突的类名。因此没有应用相应的样式属性。

我想问的是……

有没有办法将 CSS 文件仅应用于特定组件而不应用于任何其他组件?(例如将 CSS 文件范围限定到特定 div)

import React , {Component} from 'react';
import Page1 from './Page1';
import Page2 from './Page2';

class WorksLarge extends Component {
  constructor(props) {
    super(props);
    this.state = {}
  }

  render() {
    return (
      <div className="works">
          ///some code
        </div>
        <div className="works__preview">
          <Page2 /> //here I call the required Component
          <Page1 /> 
        </div>
      </div>
    )
  }
}


export default WorksLarge;

这是组件代码

import React , {Component} from 'react';
import './page1.css';
import img1 from './img/page1-img-1.jpg';

class Page1 extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(
      <div className="body-container">
         ///Some code
      </div>
    )
  }
}

export default Page1;

【问题讨论】:

    标签: css reactjs jsx


    【解决方案1】:

    是的,您可以使用 @material-ui/styles 包。您可以为特定组件添加 CSS。请检查我的组件的附加代码。

    import React from 'react';
    import PropTypes from 'prop-types';
    import { makeStyles } from '@material-ui/styles';
    import { Snackbar, SnackbarContent, colors, IconButton } from '@material-ui/core';
    import CheckCircleIcon from '@material-ui/icons/CheckCircleOutlined';
    import CancelCircleIcon from '@material-ui/icons/CancelOutlined';
    import CloseIcon from '@material-ui/icons/Close';
    import clsx from 'clsx';
    
    const useStyles = makeStyles(theme => ({
      errorContent: {
        backgroundColor: colors.red[600]
      },
      successContent: {
        backgroundColor: colors.green[600]
      },
      message: {
        display: 'flex',
        alignItems: 'center'
      },
      icon: {
        marginRight: theme.spacing(2)
      }
    }));
    
    const CustomSnackbar = props => {
      const { open, onClose, type, message} = props;
    
      const classes = useStyles();
    
      return (
        <Snackbar
          anchorOrigin={{
            vertical: 'top',
            horizontal: 'center'
          }}
          autoHideDuration={6000}
          onClose={onClose}
          open={open}
          className={clsx(classes.Snackbar, 'Snackbar')}
        >
          <SnackbarContent
            className={clsx((type === 'Success' ? classes.successContent : classes.errorContent), 'msgContent')}
            message={
              <span className={clsx(classes.message, 'message')}>
                {type === 'Success' ? 
                  <CheckCircleIcon className={clsx(classes.icon, 'icon')} />
                  : 
                  <CancelCircleIcon className={clsx(classes.icon, 'icon')} />
                }
                  {message}
              </span>
            }
            action={[
              <IconButton key="close" aria-label="close" color="inherit" onClick={onClose}>
                <CloseIcon className={classes.closeIcon} />
              </IconButton>,
            ]}
            variant="elevation"
          />
        </Snackbar>
      );
    };
    
    CustomSnackbar.propTypes = {
      onClose: PropTypes.func.isRequired,
      open: PropTypes.bool.isRequired,
      type: PropTypes.string.isRequired,
      message: PropTypes.string.isRequired
    };
    
    CustomSnackbar.defaultProps = {
      open: true,
      onClose: () => {},
      type: 'Success',
      message: 'Successfully saved changes!'
    };
    
    export default CustomSnackbar;
    

    【讨论】:

      【解决方案2】:

      有不同的方法来实现这一点,我喜欢使用样式化组件,有一些库,例如https://styled-components.com/ 或 Material UI 样式化组件 API(我更喜欢)https://material-ui.com/styles/basics/#styled-components-api

      还有其他库,例如 Emotion,因此您可以选择自己喜欢的库。

      您在那些库中(主要)用 JS 编写 CSS,这在语法上与常规 CSS 略有不同,但功能更强大,所以如果您不熟悉,我建议您检查一下!

      Material UI 样式组件示例(来自他们的文档):

      import React from 'react';
      import { styled } from '@material-ui/core/styles';
      import Button from '@material-ui/core/Button';
      
      const MyButton = styled(Button)({
        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 StyledComponents() {
        return <MyButton>Styled Components</MyButton>;
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-16
        • 1970-01-01
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 2013-03-16
        • 1970-01-01
        • 2021-11-26
        • 2019-09-12
        相关资源
        最近更新 更多