React error Line 18:样式属性值必须是一个对象react / style-prop-object

Alt*_*ian 5 html5 image reactjs

我正在尝试在图像周围换行,如果我使用以下代码:

<div className="container">
         <img src={myImageSource} alt="swimmer" height="300" width="300" style="float: left" />
         <p> This is where the other text goes about the swimmer</p>
 </div>
Run Code Online (Sandbox Code Playgroud)

现在,我知道这style="float: left"是html5。但是,如果我使用以下代码:

<div className="container">
         <img src={myImageSource} alt="swimmer" height="300" width="300" align="left" />
            <p> This is where the other text goes about the swimmer</p>
 </div>
Run Code Online (Sandbox Code Playgroud)

有用!为什么我不能在React中使用样式?

Akr*_*ion 18

问题是您将样式作为 aString而不是Object. React 希望你以对象表示法传递样式:

style={{ float:`left` }}  // Object literal notation
Run Code Online (Sandbox Code Playgroud)

或者另一种方式是:

const divStyle = {
  margin: '40px',
  border: '5px solid pink'
};

<div style={divStyle}>   // Passing style as an object
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅文档


小智 11

您仍然可以在反应中使用样式。尝试: style={{float: 'left'}}


MiF*_*vil 6

如果属性(例如'align-self')具有特殊字符,则还需要对属性名称使用单引号,例如

style={{'align-self':'flex-end'}} 
Run Code Online (Sandbox Code Playgroud)

您可能会看到警告“不支持的样式属性 align-self。您的意思是 alignSelf?”,但样式已正确复制到生成的 html align-self: flex-end;