[英]Define variables in styled-components
Is it possible to define a variable inside a styled-components
component?是否可以在
styled-components
组件中定义变量?
Hopefully the code below (not working) shows what I'm after:希望下面的代码(不工作)显示了我所追求的:
const Example = styled.div`
${const length = calc(vw - props.someValue)}
width: ${length};
&.disable {
width: ${length};
}
`
This code will not work, as far as I understand Template Literal's guidelines. 就我所了解的Template Literal指南而言,此代码将不起作用。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
Template literals are those backticks that wraps the code you have after the div
. 模板文字是那些在
div
之后包装您的代码的反引号。
const Example = styled.div` here `
常量示例= styled.div` 这里 `
Let's say: 比方说:
const num = 10;
console.log(\`The number I saved in a variable is ${num}\`);
The output log would be: "The number I saved in a variable is 10"
输出日志将是:
"The number I saved in a variable is 10"
Inside Template literals you can have an expressions . 在Template文字内部,您可以有一个表达式 。 Declaring a variable is not possible inside because its a statement: http://2ality.com/2012/09/expressions-vs-statements.html
在内部无法声明变量,因为它的声明如下: http : //2ality.com/2012/09/expressions-vs-statements.html
So this question is more about the core of Javascript then styled-components
in itself. 因此,这个问题更多地是关于Javascript核心,然后是
styled-components
本身。
A possible workaround using CSS variables but no ie support. 使用CSS变量但不提供支持的可能解决方法。
const Example = styled.div`
--length: calc(vw - props.someValue)
width: calc(var(--length));
&.disable {
width: calc(var(--length));
}
`
I recently wanted to do something like this.我最近想做这样的事情。 But in my case, I had to compute new var with the use of props only and not with vw.
但就我而言,我必须仅使用 props 而不是 vw 来计算新的 var。
I achieved this by defining a short function.我通过定义一个简短的 function 来实现这一点。
const getLength = (baseValue, someValue) => {
// you can do any complex or multiline calculation here
return baseValue - someValue;
}
const Example = styled.div`
width: ${(props) => getLength(props.baseValue, props.someValue)};
&.disable {
width: ${(props) => getLength(props.baseValue, props.someValue)};
}
`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.