The text starts here~
Overview
In React, when we pass a string for the style
property of an element, the "Style prop value must be an object" warning is generated. To resolve the warning, use a property-to-value mapping. For example, style={{paddingLeft: '15px'}}
.
Here is an example to show how the error occurs.
// App.js
const App = () => {
// ⛔️ Style prop value must be an object eslint(react/style-prop-object)
return (
<div>
<h1 style="margin-left: 4rem">Hello world</h1>
</div>
);
};
export default App;
map
The problem with the above code is that we are passing a string for the style
attribute of the h1
element. Instead, style
properties should pass a mapping from properties to values.
const App = () => {
return (
<div>
<h1
style={{
marginLeft: '4rem',
fontSize: '20px',
padding: '20px',
backgroundColor: 'salmon',
color: 'white',
}}
>
Hello world
</h1>
</div>
);
};
export default App;
It should be noted that here we use 2 pairs of curly braces. The outer curly braces are the evaluation of an expression, and the inner curly braces are objects that contain property names and values.
You can also use logic to calculate specific values.
const App = () => {
return (
<div>
<h1
style={{
marginLeft: 2 + 2 + 'rem',
fontSize: Math.random() > 0.5 ? '20px' : '40px',
padding: '20px',
backgroundColor: 'salmon',
color: 'white',
}}
>
Hello world
</h1>
</div>
);
};
export default App;
extract
You can also extract an object containing properties and values into a variable.
const App = () => {
const h1Styles = {
marginLeft: 2 + 2 + 'rem',
fontSize: Math.random() > 0.5 ? '20px' : '40px',
padding: '20px',
backgroundColor: 'salmon',
color: 'white',
};
return (
<div>
<h1 style={h1Styles}>Hello world</h1>
</div>
);
};
export default App;
Note that CSS property names must be camelCase. Another way is to write your CSS in a file with the extension .css
b6385556e1e1a063a7acf9bf798c76a4--- and use the className
attribute to style your element.
Here's how we moved the style of the h1
element into a class in a file named App.css
.
.my-h1 {
margin-left: 4rem;
font-size: 20px;
padding: 20px;
background-color: salmon;
color: white;
}
We can then import the css
file and use the my-h1
class.
import './App.css';
const App = () => {
return (
<div>
<h1 className="my-h1">Hello world</h1>
</div>
);
};
export default App;
This is an alternative to inline styles. Note that this property is called className
and not class
. The reason is: class
is a reserved word in JavaScript. class
Keywords are used to declare ES6 classes.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。