React 内联样式样式道具需要从样式属性到值的映射,而不是字符串

我试图在 React 应用程序中设置内联样式:

<span className="myClass" style={{float : 'left', paddingRight : '5px'}} > </span>

React 告诉我:

Uncaught Invariant Violation: The style prop expects a mapping from 样式属性设置为值,而不是字符串, Style = {{ markight: space + ‘ em’}}当使用 JSX 时 是由“判决视图”呈现的

我不太确定这是什么意思。

PS: I have tried different versions, so I did paddingRight: 5 as well as paddingRight: 5 + 'px' as well as paddingRight : 5px, but I didn't have any success!

163121 次浏览

使用“ 风格<是的trike>是的”道具,而不是风格

<span className="myClass" style=\{\{float : 'left', paddingRight : '5px'}} > </span>

这里有一个来自 W3Schools 的很好的参考,它也向你展示了如何创建一个带有样式信息的对象,并在 style 属性中引用它: 关于如何使用 CSS 样式化 React 的参考

This is the way how you can define and use inline style with react.

/**
* Style definitions.
*/
const STYLE = {
infoColor: {
color: 'green'
},
warningColor: {
color: 'orange'
},
errorColor: {
color: 'red'
}
};


/**
* Component
*/
class Welcome extends React.Component {


/**
* Rendering into the DOM.
*/
render() {
return (
<div>
<h2 style={STYLE.infoColor}>Welcome!</h2>
)
}
}

有一些方法可以设置反应组件的样式。

Https://facebook.github.io/react/docs/context.html

Https://github.com/facebookincubator/create-react-app

  1. 使用 style={css_object}style=\{\{color: this.props.color}}

  2. using className="your-class-name"

反应 REPL

https://jscomplete.com/repl

1样式对象

// <span style={styles}>


const styles = {
color: "red",
background: "#0f0",
fontSize: "32px"
};


const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span style={styles}>{props.age}</span> yeas old!
</div>
);
};


const infos = {
name: "xgqfrms",
age: 23
};


ReactDOM.render(<BTN {...infos} />, mountNode);








// <span style=\{\{color: styles.color}}>


const styles = {
color: "red",
background: "#0f0",
fontSize: "32px"
};


const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span style=\{\{color: styles.color}}>{props.age}</span> yeas old!
</div>
);
};


const infos = {
name: "xgqfrms",
age: 23
};


ReactDOM.render(<BTN {...infos} />, mountNode);

2 className & stylesheet.css

import './styles.css';


/*
.classname-color{
color: "red";
background: "#0f0";
}
*/




const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span className="classname-color">{props.age}</span> yeas old!
</div>
);
};


const infos = {
name: "xgqfrms",
age: 23
};


ReactDOM.render(<BTN {...infos} />, mountNode);
.classname-color{
color: "red";
background: "#0f0";
}

不要用双引号或字符串包装\{\{}

JSX 和 HTML 是不同的,参见 下图来自 Udemy: Difference between JSX and HTML

在 HTML 中是这样的

<div style="background-color: red;"></div>

In JSX you write

<div style=\{\{ backgroundColor: 'red' }}></div>

两者的条件内联格式都不同。

when we use inline styling in react we should always use style=\{\{styleproperties}}

错误:

<input style="margin:0 15px 0 0"/>

Solution:

<input style=\{\{margin:"0 15px 0 0"}}/>