2017-02-22 119 views
1

我有自定義組件,其中我映射屬性。 在這個組件中,我有標籤分配了CSS類。 但我也想要這個標籤可選的內聯樣式。 問題是,在反應中我需要用大括號包圍內聯樣式,我無法將它們轉義或在組件中正確設置它們。如何解決這個問題?作爲React組件中的屬性的Css內聯樣式

代碼從組件:

const CustomComponent = ({items, name}) => (
    <fieldset> 
     {items 
      .map((item, index) => ({item, id: `${name || 'dod'}-${item.value || index}`})) 
      .map(({item, id}) => 
       <div key={id} 
        className="className1"> 
        <input 
         id={id} 
         name={name} 
         type="text" 
        /> 
        <label htmlFor={id} className="className" style={item.style}> 
         {item.label} 
        </label> 
       </div> 
      )} 
    </fieldset> 
); 

從渲染.jsx

<CustomComponent    
     name="name" 
     items={[{ 
      value: 'value', 
      label: 'label', 
      style: {{display: 'inline'}}  -> not working 
     }]} 
    /> 
+0

你能告訴我們更多的代碼? 'item.style'的類型是什麼?它必須是一個對象文字?如果你正在映射,使用'key'。 – Noctisdark

回答

1

當您直接在Virutal DOM Object內時,您只需要包含第一個{}<... items={object} .../>然後物體的寫法應與其他Object Literals完全相同。這就是說,你需要{display: 'inline'}而不是{{display: 'inline'}}

<CustomComponent    
    name="name" 
    items={[{ 
     value: 'value', 
     label: 'label', 
     style: {{display: 'inline'}}  -> not working //use {display: 'inline'} 
    }]} 
/> 

我做這一筆在Codepen,您可以檢查它Here

+1

是的它的工作原理,感謝您的幫助:) – user1974566

+0

很高興可以使用。 – Noctisdark

1

你的樣式屬性代碼必須是一個對象文本,像這樣:

item.style = { 
display: 'inline' 
} 
1

在反應你可以用JS對象的形式來定義你的樣式,比如

style: {{display: 'inline'}} 
0

您可以抽象這進一步,有一個JS文件來保存你的頁面的所有樣式:

const styles = { 
    myElement: { 
    display: 'inline' 
    } 
} 

然後在代碼...

<Component style={styles.myElement} />