我有以下内容:
style={{ width: 'calc(100% - 300px)' }}
我想做这样的事情:
let myWidth: number = 300;
style={{ width: 'calc(100% - {myWidth})' }}
以上示例失败,我该如何完成?
答案 0 :(得分:1)
使用模板字符串:
const myWidth: number = 300;
style = {{ width: `calc(100% - ${myWidth}px)` }}
答案 1 :(得分:1)
将myWidth
设置为如此字符串:let myWidth = '300px';
请尝试下面的代码段或查看此CodePen Demo
const App = () => {
let myWidth = "300px";
return (
<div className="full">
<div className="inner" style={{ width: `calc(100% - ${myWidth})` }}>
Hi
</div>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
// log .inner div style
console.log(document.querySelector(".inner").style.width);
&#13;
.full {
width: 100%;
background: black;
height: 100vw;
}
.inner {
background: white;
font-size: 2em;
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>
&#13;