javascript - 如何从 react Prop 传递到 sass 变量?

标签 javascript css reactjs sass frontend

我正在使用 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'));

谢谢 !

最佳答案

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

  • npm i styled-components
  • 在您的 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>
      )
    }
    

    关于javascript - 如何从 react Prop 传递到 sass 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50042053/

    相关文章:

    ios - 数字在iphone模拟器中以蓝色字体显示

    javascript - 使 Axios post 来自 Gatsby JS 的请求

    javascript - 与 setState 回调相比,使用 componentDidUpdate 有什么优势?

    javascript - ReactJS:为什么约定在 componentDidMount 上获取数据?

    javascript - 从ajax get请求接收到的数据

    javascript - Angular 拼接在移动 fromIndex、toIndex 时覆盖元素

    html - 如何使用CSS在两个文本之间切换

    html - 在使用填充来定位内容时,如何使我的网站在每个屏幕上看起来都一样?

    JavaScript 数组 + 数组 = 字符串?

    javascript - 使用数据还是放入 Javascript?