【问题标题】:How do i bind a css stylesheet to only 1 react component?如何将 css 样式表绑定到仅 1 个反应组件?
【发布时间】:2021-04-14 13:40:50
【问题描述】:

我正在使用 React 模板,我在其中使用一些 react 和简单的 HTML 插入了一个购物车站点(代码在问题下方)。我还有一个 index.css 文件,其中包含购物车的 css。我的目标是仅在购物车站点中实现 CSS。 我试图在我的购物车中“导入'./index.css'。 问题如下:在渲染购物车后,css 也被应用到了其他所有站点。 怎么可能只在购物车中使用css代码?

import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { addToCart, removeFromCart } from '../../frontend/actions/cartActions';
import MessageBox from '../../frontend/MessageBox';
import { useLocation } from 'library/hooks/useLocation';


export default function CartScreen(props) {

  //  Namen
  var a = window.location.href; 
  var b = a.substring(a.indexOf("?")+1)
  const productId = b;
  console.log(productId)


  // redux store
  const cart = useSelector((state) => state.cart);
  const { cartItems, error } = cart;


  const dispatch = useDispatch();
  useEffect(() => {
    if (productId) {
      dispatch(addToCart(productId));
    }
  }, [dispatch, productId]);

  const removeFromCartHandler = (id) => {
    // delete action
    dispatch(removeFromCart(id));
  };

  const checkoutHandler = () => {
    props.history.push('/signin?redirect=shipping');
  };
  return (
      
    <div className="row top">
      <div className="col-2">
        <h1>Shopping Cart</h1>
        {error && <MessageBox variant="danger">{error}</MessageBox>}

        {/* display cart or message if empty */}
        {cartItems.length === 0 ? (
          <MessageBox>
            Cart is empty. <Link to="/">Go Shopping</Link>
          </MessageBox>
        ) : (
          <ul>
            {cartItems.map((item) => (
              <li key={item.product}>
                <div className="row">
                  <div>
                    <img
                      src={item.image}
                      alt={item.name}
                      className="small"
                    ></img>
                  </div>
                  <div className="min-30">
                    <Link to={`/product/${item.product}`}>{item.name}</Link>
                  </div>
                  <div>
                    <select
                      value={item.qty}
                      onChange={(e) =>
                        dispatch(
                          addToCart(item.product, Number(e.target.value))
                        )
                      }
                    >
                      {[...Array(item.countInStock).keys()].map((x) => (
                        <option key={x + 1} value={x + 1}>
                          {x + 1}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>${item.price}</div>
                  <div>
                    <button
                      type="button"
                      onClick={() => removeFromCartHandler(item.product)}
                    >
                      Delete
                    </button>
                  </div>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
      <div className="col-1">
        <div className="card card-body">
          <ul>
            <li>
              <h2>
                Subtotal ({cartItems.reduce((a, c) => a + c.qty, 0)} items) : $
                {cartItems.reduce((a, c) => a + c.price * c.qty, 0)}
              </h2>
            </li>
            <li>
              <button
                type="button"
                onClick={checkoutHandler}
                className="primary block"
                disabled={cartItems.length === 0}
              >
                Proceed to Checkout
              </button>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
}

【问题讨论】:

  • 如果您有多个用于不同站点的 CSS 文件,您是否考虑过进一步描述您的 CSS 也只是该文件独有的 div 类的一部分?我通常让我的外部 div 类似于&lt;div className='CartScreen'&gt;...&lt;/div&gt;,然后我的 CSS 类似于.CartScreen .min-30 {}
  • 我没有。老实说,我对 css 的体验很差。你的意思是我可以抓住我所有的 css,把它放在花括号中并将它标记为 .cartScreen{-all my css-} (与 div 中的名称相同)?
  • 不,我的意思是,当您声明一组 CSS(在花括号内)适用于哪些类(或 id 或其他)时,您可以包含多个类,并且仅当所有类(包括父类)都适用时,它才会应用 CSS。如果您有 CSS 的部分示例,可能会更容易解释。
  • 正文{边距:0;高度:100vh;字体大小:1.6rem;字体系列:Helvetica、Arial、无衬线字体; -webkit-font-smoothing:抗锯齿; -moz-osx-font-smoothing:灰度; } #root { 高度:100%; } /* 布局 */ .grid-container { display: grid;网格模板区域:“页眉”“主”“页脚”;网格模板列:1fr;网格模板行:5rem 1fr 5rem;高度:100%; } 标题 { 网格区域:标题;背景颜色:#203040; (这是 CSS 的一小部分。整个类有 400 多行。)
  • 好的,所以对于第一个,如果您的渲染返回的顶部 div 是我之前提到的,那么 CSS 可以是 body .CartScreen { margin: 0, ...

标签: css reactjs rendering


【解决方案1】:
  1. 导入'./index.css'

  2. 给 html 中的 div 一个特定的名称:&lt;div className="cartScreen"&gt;

  3. 在css中,指定应该使用样式的元素:

    body .cartScreen{
        margin: 0;
        height: 100vh;
        font-size: 1.6rem;
        font-family: Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
    }
    

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 2020-08-14
    • 2019-09-12
    • 1970-01-01
    • 2016-07-15
    • 2021-05-18
    • 1970-01-01
    • 2012-05-27
    相关资源
    最近更新 更多