【问题标题】:How to pass from a react props to a sass variable?如何从反应道具传递到 sass 变量?
【发布时间】:2018-10-07 02:21:18
【问题描述】:

我正在使用 React 和 SASS,我有一个立方体组件,我想用动态宽度渲染它。但是,我在我的 .scss 中使用这个宽度。有一个例子。

我的组件:

<Cube style={{ width: '100px' }} />
<Cube style={{ width: '70px' }} />
<Cube style={{ width: '20px' }} />

我的 style.scss:

$cubeWidth: 150px;
$cubeHeight: $cubeWidth;
#cube {
      width: $cubeWidth;
      height: $cubeHeight;
}

// In this cube, I have -of course- 6 faces, and I operate in my style.scss:

.cubeFace1 {
     transform: translateZ($cubeWidth / 2);
}
... etc

如何让我的 $cubeWidth 等于我的动态宽度? 此外,.scss 在 index.js 中加载如下:

// React index.js

import './css/style.scss';

render(<Router />, document.getElementById('root'));

谢谢!

【问题讨论】:

    标签: javascript css reactjs sass frontend


    【解决方案1】:

    不可能将 react props 传递给 sass 变量。但是,您可以使用样式组件:https://styled-components.com/docs/basics#installation

    1. npm i styled-components
    2. 在您的 Cube 组件代码中,在顶部的 import 语句之后添加,
    const Cube = styled.div`
          width: props.cubeWidth;
          height: props.cubeHeight;
    `;
    
    const CubeFaceOne = styled.span`
          transform: translateZ(props.cubeWidth / 2);
    `;
    

    使用这种方法,Cube 和 CubeFace 需要被拆分成两个独立的组件,并且会以这种形式呈现,

    render() {
      return (
        <Cube>
          <CubeFaceOne />
          <CubeFace />
          <CubeFace />
          ...
        </Cube>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-06
      • 2017-05-20
      • 2021-11-02
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多