内联样式不起作用 ReactJS [英] Inline style is not working ReactJS

查看:82
本文介绍了内联样式不起作用 ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 React.为什么不能在组件内部的返回中使用样式?

错误:

<块引用>

style 属性需要从样式属性到值的映射,不是字符串.例如,style={{marginRight: spatial + 'em'}} 当使用 JSX.这个 DOM 节点由 Home 渲染.

<div className="single_slide" style="background-image: url(../images/WinterCalling_2016.jpg);">

我也试过这个:

<div className="single_slide" style={{background-image: 'url(../images/WinterCalling_2016.jpg)'}}>

<div className="single_slide" style={{background-image: url(../images/WinterCalling_2016.jpg)}}>

任何有关此语法的帮助将不胜感激.其他人发帖说他们改变风格说风格,但这似乎也不起作用.

解决方案

来自 DOC:

<块引用>

在 React 中,内联样式没有指定为字符串.相反,他们用一个对象指定,该对象的键是 camelCased 版本的样式名称,其值为样式的值,通常为字符串.

所以用 backgroundImage 代替 background-image.

例如:

padding-top --->填充顶部填充左--->填充左右边距--->右边距...

<块引用>

如何指定内联样式?

我们需要将一个对象传递给 style 属性,该属性将以键值对的形式包含所有值.

像这样:

更新:

我们可以使用模板文字在内部传递一个变量网址,像这样:

I am trying to learn React. Why can you not use style inside of a return inside of a component?

The Error:

The style prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX. This DOM node was rendered by Home.

<div className="single_slide" style="background-image: url(../images/WinterCalling_2016.jpg);">

I have also tried this also:

<div className="single_slide" style={{background-image: 'url(../images/WinterCalling_2016.jpg)'}}>

or

<div className="single_slide" style={{background-image: url(../images/WinterCalling_2016.jpg)}}>

Any help with this syntax would be greatly appreciated. Other people posted they change style to say styles but that did not seem to work either.

解决方案

From DOC:

In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string.

So instead of background-image use backgroundImage.

For example:

padding-top      --->     paddingTop

padding-left     --->     paddingLeft

margin-right     --->     marginRight

...

How to specify the inline style?

We need to pass a object to style attribute which will contains all the values in form of key-value pair.

Like this:

<div 
    style={{
       backgroundImage: 'url(../images/WinterCalling_2016.jpg)', 
       marginTop: 20}}
>

Update:

We can use template literals to pass a variable inside url, like this:

<div style={{backgroundImage: `url(${image1})`}}>

这篇关于内联样式不起作用 ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆