【问题标题】:How can I apply fallback style properties to a React JS component?如何将后备样式属性应用于 React JS 组件?
【发布时间】:2015-01-06 11:52:03
【问题描述】:
我想将后备样式属性应用于组件。例如:
var inlineStyle = {
display: '-webkit-box',
display: '-webkit-flex',
display: '-moz-box',
display: '-moz-flex',
display: '-ms-flexbox',
display: 'flex'
}
return <div style={inlineStyle}>{divContent}</div>;
有没有办法做到这一点?目前他们被忽略了。
【问题讨论】:
标签:
javascript
css
reactjs
【解决方案2】:
每个声明都会覆盖最后一个声明,因为它们都具有相同的键名。当属性 value 需要前缀时,对象字面量语法会出现问题,即使在今天(2016 年 9 月 6 日)也没有成熟的解决方案。
我自己,需要解决这个问题,想留在 CSS-in-JS 领域(为完全自包含的组件欢呼)而不是添加构建步骤,所以制作了一个名为 Style It 的包以保持简单让您编写 CSS。
npm install style-it --save
函数语法 (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return Style.it(`
.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
justify-content: space-around;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin-top: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
`,
<ul class="flex-container">
<li class="flex-item">1</li>
<li class="flex-item">2</li>
<li class="flex-item">3</li>
<li class="flex-item">4</li>
<li class="flex-item">5</li>
<li class="flex-item">6</li>
</ul>
);
}
}
export default Intro;
JSX 语法 (JSFIDDLE)
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
.flex-container {
padding: 0;
margin: 0;
list-style: none;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-flow: row wrap;
justify-content: space-around;
}
.flex-item {
background: tomato;
padding: 5px;
width: 200px;
height: 150px;
margin-top: 10px;
line-height: 150px;
color: white;
font-weight: bold;
font-size: 3em;
text-align: center;
}
`}
<ul class="flex-container">
<li class="flex-item">1</li>
<li class="flex-item">2</li>
<li class="flex-item">3</li>
<li class="flex-item">4</li>
<li class="flex-item">5</li>
<li class="flex-item">6</li>
</ul>
</Style>
}
}
export default Intro;
HTML / CSS 来自 Chris Coyier 的 A Complete Guide to Flexbox 帖子。