简体   繁体   English

React:使用内联样式设置所有元素的样式

[英]React: style all elements with inline styles

I want to make all of my elements border-box.我想让我所有的元素边框框。 I want to do this:我想做这个:

* {
  box-sizing: border-box;
}

How is that possible to do in with React's inline styles?这怎么可能与 React 的内联样式有关? I don't want to write that rule in each component...我不想在每个组件中都写那个规则......

This is ill-advised since CSS will be much more efficient, manageable, and flexible.这是不明智的,因为 CSS 将更加高效、易于管理和灵活。 But if you REALLY wanted to have global inline React styles, I might do it like this:但是如果你真的想拥有全局内联 React 样式,我可能会这样做:

var App = React.createClass({
    globalStyle: {
        boxSizing: "border-box"
    },
    render() {
        return (
            <div>
                <MyComponent globalStyle={this.globalStyle} />
            </div>
        );
    }
});

var MyComponent = React.createClass({
    style: {
        border: "1px solid black"
    },
    render() {
        return (
            <div style={Object.assign({}, this.props.globalStyle, this.style)}></div>
        );
    }
});

Basically pass global style down to components as props and have them incorporate it there.基本上将全局样式作为道具传递给组件,并让它们在那里合并。

Note that Object.assign() 's first parameter is a new empty object (so that we don't accidentally mutate our others) and that this.style comes last (so that it overrides any global styles.)请注意Object.assign()的第一个参数是一个新的空对象(这样我们就不会意外地改变我们的其他对象)并且this.style最后出现(这样它会覆盖任何全局样式。)

If you wanted the global style to change, you'd do it with React's component state instead and use getInitialState etc. I suppose that might actually be the only reason you'd want to do it this way.如果你想在全球的风格变化,你会与之反应的成分做的state ,而不是和使用getInitialState等我想这实际上可能是你想要做这样的唯一原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM