我正在使用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'));
谢谢!
答案 0 :(得分:1)
不可能从react道具传递到sass变量。但是,您可以使用样式组件:https://styled-components.com/docs/basics#installation
npm i styled-components
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>
)
}