2017-05-31 35 views
1

我試圖設計一個React組件的樣式,以便各個元素可以水平或垂直樣式(使用非flexbox解決方案)。具有多個佈局的React組件

如何將樣式傳遞到要將各個樣式應用於組件的子元素的組件?

例如爲了生產 horizontal

vertical

如果只爲水平相關的風格是:

input, button { 
    vertical-align:middle; 
} 

button { 
    margin-left: 10px; 
} 

,並且只能用於垂直佈局相關的是:

.form-control { 
    display: inline-block; 
} 

.btn { 
    display: block; 
    margin: auto; 
} 

和組件是:

class Form extends React.Component { 

    render() { 
    return (
     <form className="form-group"> 
     <input className="form-control" type="text" placeholder="St. George, Utah"/> 
     <button className="btn">Get Weather</button> 
     </form> 
    ); 
    } 
} 
+0

您可以傳遞一個布爾屬性來確定它是否應該是水平的,並在按鈕組件本身的JavaScript中切換「內嵌」樣式。 –

回答

1

有幾種方法可以解決這個問題。

第一個,更受控制的一個與邁克爾里昂的推薦有關。將一個道具傳遞給確定組件佈局是垂直還是水平的組件。

當您收到該變量時,您可以添加類到您的組件中,以根據需要進行設置。

你的組件可以是這樣的:

class Form extends React.Component { 

    render() { 
    let buttonClassName = "btn" + (this.props.isVertical)? " vertical-button" : "horizontal-button"; 
    let inputClassName = "form-control" + (this.props.isVertical)? " vertical-input": "hotizontal-input"; 
    return (
     <form className="form-group" > 
     <input className={inputClassName} type="text" placeholder="St. George, Utah"/> 
     <button className={buttonClassName} >Get Weather</button> 
     </form> 
    ); 
    } 
} 

你的CSS可以是這個樣子:

/* For the vertical form */ 

.vertical-input { 
    display: inline-block; 
} 

.vertical-button { 
    display: block; 
    margin: auto; 
} 

/* For the horizontal form */ 

.horizontal-input, .horizontal-button { 
    vertical-align:middle; 
} 

.horizontal-button { 
    margin-left: 10px; 
} 

或者you can pass a style object to the style attribute of the HTML tags直接取決於其標誌收到。也就是說,如果您收到this.props.isVertical您創建一個JS對象,想是這樣的:

let inputStyle = { display: "inline-block" }; 

,並通過它t時的標籤,像這樣:

<input className="form-control" type="text" style={inputStyle} placeholder="St. George, Utah" /> 

快速注:該對象上的按鍵,你傳遞給HTML標籤需要被camelCased而不是虛線分隔。所以,margin-left變成marginLeft

+1

非常感謝。 – Yunti

+1

爲了能夠在將來重載,我會在類的解決方案上犯錯,內聯樣式非常具體,只能被'!important'覆蓋。 –