[英]ReactJS: Defining style attributes with functions
is it possible to define CSS inline styles by a function? 是否可以通过函数定义CSS内联样式? I'm trying to do this:
我正在尝试这样做:
render() {
var listStyle = {
position: "relative",
display: () => {
console.log("Still alive")
if(this.state.open) {
return "block";
}
else return "none";
}
return <li style={listStyle}>
.....
}
To no avail. 无济于事。 It won't even log "Still alive", so the function doesn't even execute.
它甚至不会记录“仍然存在”,因此该功能甚至不会执行。 I know there's no problem with assigning functions to objects in JS, so what gives?
我知道将功能分配给JS中的对象没有问题,那有什么用呢?
You can try to do like this, more simple 您可以尝试这样做,更简单
var listStyle = {
position: "relative",
display:this.state.open?'block':'none'
}
I think the style object just access the value in properties 我认为样式对象只是访问属性中的值
but if you really like function. 但如果您真的喜欢功能。 you can use self-executing anonymous function to make it run
您可以使用自执行匿名函数使其运行
var listStyle = {
position: "relative",
display: (()=>{
console.log('alive')
if(this.state.open){
return 'block'
}else{
return 'none'
}
})()
}
You can go with this 你可以这样
const listStyle = {
position: 'relative'
}
const checkDisplay = open => {
if (open) {
return "block"
}
return "none";
}
<li style={{...listStyle, display: checkDisplay(this.state.open)}}></li>
Let me know if that work. 让我知道是否可行。 Hope that can help you :)
希望能对您有所帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.