ReactJS嵌套内联样式

时间:2015-10-05 09:26:19

标签: css inheritance nested reactjs components

我在ReactJS中有一个名为SearchBar的组件

var SearchBar = React.createClass({
    render: function () {
        return (
            <div style={{width:'100%',position:'0',backgroundColor:'darkOrange'}}>
                <div style={[styles.dataBlock,styles.header]}>
                    <h1>MOVIE</h1>
                </div>
                <div styles={[styles.dataBlock,styles.searchForm]}>
                    <input style={[styles.dataBlock,styles.searchForm,styles.searchField]}
                        type="text" placeholder="Enter search term"/>
                </div>
            </div>
        );
    }
});

以下是styles

var styles = {
    dataBlock: {
        width: '100%',
        height: '100%',
        margin: '0 auto',
        fontFamily: 'Helvetica',
        textAlign: 'center'
    },
    header: {
        width: 'inherit',
        marginLeft: 'auto',
        marginRight: 'auto'
    },
    searchField: {
        width: 'inherit'
    },
    searchForm: {
        width: '90%',
        marginLeft: 'auto',
        marginRight: 'auto'
    }
};

似乎这些样式不起作用,我在input中声明width:90% textform没有styles。我想使用样式继承,以便在style中放入一系列内联样式。我在这里弄错了吗?如何在ReactJS中继承样式?

1 个答案:

答案 0 :(得分:1)

documentation

  

在React中,内联样式未指定为字符串。相反,他们   使用一个对象指定,该对象的键是camelCased版本的   样式名称,其值为样式的值,通常为字符串

它明确指出style需要是键值对的对象,而不是数组。它背后没有魔力。样式对象可以用vanilla JS或一些实用程序库组成,如lodashunderscore,jQuery,任何适合你项目的东西。

// Vanilla JS
<div style={ Object.assign( styles.dataBlock, styles.searchForm ) }> ...
// Lodash
<div style={ _.assign( styles.dataBlock, styles.searchForm ) }> ...
相关问题