2017-09-17 32 views
-1

我有以下几点:如何将“px”添加到calc函数中?

style={{ width: 'calc(100% - 300px)' }} 

我想要做这样的事情:

let myWidth: number = 300; 
style={{ width: 'calc(100% - {myWidth})' }} 

上面的例子失败了,我怎么做到呢?

回答

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);
.full { 
 
    width: 100%; 
 
    background: black; 
 
    height: 100vw; 
 
} 
 

 
.inner { 
 
    background: white; 
 
    font-size: 2em; 
 
}
<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>

1

使用模板字符串:

const myWidth: number = 300; 
style = {{ width: `calc(100% - ${myWidth}px)` }} 
+0

不工作.. – tweetypi

+0

在变量 –

+0

看起来好像不接受$ {myWidth}作为字符串文字后,检查'px',该字符串的结果结束为calc(100% - $ myWidth} px)' – tweetypi