在React中设置行内样式:
- 将元素的
style
prop设置为对象。 - 为元素的样式设置指定的属性和值。
- 比如说,
<div style={{backgroundColor: 'salmon', color: 'white'}}>
// App.js
const App = () => {
const stylesObj = {
backgroundColor: 'lime',
color: 'white',
};
const elementWidth = 150;
return (
<div>
{/* 👇️ set inline styles directly */}
{/* 👇️ 直接设置行内样式 */}
<div style={{backgroundColor: 'salmon', color: 'white'}}>
Some content
</div>
<br />
{/* 👇️ set inline styles using an object variable */}
{/* 👇️ 使用对象变量设置行内样式 */}
<div style={stylesObj}>Some content</div>
<br />
{/* 👇️ set inline styles conditionally using a ternary */}
{/* 👇️ 使用三元运算符设置行内样式 */}
<div
style={{
backgroundColor: 'hi'.length === 2 ? 'violet' : 'mediumblue',
color: 'hi'.length === 2 ? 'white' : 'mediumpurple',
}}
>
Some content
</div>
<br />
{/* 👇️ set inline styles interpolating a variable into a string */}
{/* 👇️ 在字符串中插入变量,来设置行内样式 */
<div
style={{
width: `${elementWidth}px`,
backgroundColor: 'salmon',
color: 'white',
}}
>
Some content
</div>
</div>
);
};
export default App;
方式
直接设置行内样式
第一个示例是直接在元素上设置行内样式。
<div style={{backgroundColor: 'salmon', color: 'white'}}>
Some content
</div>
需要注意的是,当在style
对象上设置样式时,多单词属性诸如background-color
需要设置为驼峰样式。style
属性的值被包装在两对花括号中。
行内样式的第一对花括号标志着表达式的开始,第二对花括号是包含样式和值的对象。
提取到变量中
第二个示例将样式对象提取到一个变量中。
const App = () => {
const stylesObj = {
backgroundColor: 'lime',
color: 'white',
};
return (
<div>
{/* 👇️ set inline styles using an object variable */}
<div style={stylesObj}>Some content</div>
</div>
);
};
export default App;
当你有多个元素共享相同的样式时,你可以使用该方法。
三元运算符
在React中,可以使用三元运算符来有条件地设置行内样式。
<div
style={{
backgroundColor: 'hi'.length === 2 ? 'violet' : 'mediumblue',
color: 'hi'.length === 2 ? 'white' : 'mediumpurple',
}}
>
Some content
</div>
三元运算符与if/else
语法非常相似。
问号前的部分会被计算,如果它返回一个真值(
truthy
),运算符会返回冒号前的值,否则会返回冒号后的值。
示例中的三元运算符检查字符串hi
的length
属性是否等于2
,如果等于,则返回字符串violet
作为backgroundColor
属性的值;否则返回字符串mediumblue
作为backgroundColor
属性的值。
模板字符串
在设置行内样式时,还可以用字符串插入表达式或变量。
const App = () => {
const elementWidth = 150;
return (
<div>
{/* 👇️ set inline styles interpolating a variable into a string */}
<div
style={{
width: `${elementWidth}px`,
backgroundColor: 'salmon',
color: 'white',
}}
>
Some content
</div>
</div>
);
};
export default App;