2017-05-31 36 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'覆盖。 –