簡體   English   中英

ReactJS:使用函數定義樣式屬性

[英]ReactJS: Defining style attributes with functions

是否可以通過函數定義CSS內聯樣式? 我正在嘗試這樣做:

render() {
var listStyle = {
    position: "relative",
    display: () => {
        console.log("Still alive")
        if(this.state.open) {
             return "block";
        }
        else return "none";
    }
return <li style={listStyle}>
.....
}

無濟於事。 它甚至不會記錄“仍然存在”,因此該功能甚至不會執行。 我知道將功能分配給JS中的對象沒有問題,那有什么用呢?

您可以嘗試這樣做,更簡單

var listStyle = {
    position: "relative",
    display:this.state.open?'block':'none'
}

我認為樣式對象只是訪問屬性中的值

但如果您真的喜歡功能。 您可以使用自執行匿名函數使其運行

var listStyle = {
    position: "relative",
    display: (()=>{
        console.log('alive')
        if(this.state.open){
           return 'block'
        }else{
           return 'none'
        }
    })()

}

你可以這樣

 const listStyle = {
   position: 'relative'
 }


const checkDisplay = open => {
  if (open) {
    return "block"
  }
  return "none";
}

<li style={{...listStyle, display: checkDisplay(this.state.open)}}></li>

讓我知道是否可行。 希望能對您有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM