添加存储在React类中的变量中的样式 [英] Adding style stored in a variable inside React class
问题描述
我正在尝试在我的React类中使用一些样式。我之前做过:
I'm trying to use some style inside my React class. I have done it before doing:
<div style={{background: "red"}}></div>
我想改用变量,例如:
<div style={divStyle}></div>
我的代码如下:
class HolaMundo extends React.Component {
const divStyle = {
color: 'blue',
};
render() {
return(
<div className="container" style={divStyle}>
<h1> Hola {this.props.name}</h1>
</div>
);
}
}
ReactDOM.render(<HolaMundo name="One" />, document.getElementById("app"));
但未应用样式。我怎样才能实现这个目标?
But the styles are not applied. How can I achieve this?
推荐答案
你不能在类的中间定义一个常量,这是无效的语法。根据定义 1 ,类主体只能包含方法定义,静态方法定义和空语句(;
) 2 。在方法中定义 divStyle
:
You can't define a constant in the middle of a class, that's invalid syntax. Class bodies, by definition1, can only contain method definitions, static method definitions, and empty statements (;
)2. Define the divStyle
inside a method:
class HolaMundo extends React.Component {
render() {
const divStyle = {
color: 'blue',
};
return (
<div className="container" style={divStyle}>
<h1>Hola {this.props.name}</h1>
</div>
);
}
}
1 根据ECMAScript 2015语言规范,第14.5节 - 班级定义
1Per the ECMAScript 2015 Language Specification, Section 14.5 - Class Definitions
2 Babel 目前支持类属性(使用插件)。您还可以通过构造函数为 this.style = {...}
分配实例变量,并使用访问该类中的任何位置。风格
。
2Babel currently supports class properties (with plugins). You can also assign an instance variable through the constructor, with this.style = { ... }
and access it anywhere in the class with this.style
.
这篇关于添加存储在React类中的变量中的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!