我正在尝试在我的 React 类中使用一些样式。我之前做过:
<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"));
但是没有应用样式。我怎样才能做到这一点?
最佳答案
您不能在类的中间定义常量,这是无效的语法。根据定义1,类体只能包含方法定义、静态方法定义和空语句(;
)2。在方法中定义 divStyle
:
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 语言规范,Section 14.5 - Class Definitions
2 Babel目前支持类属性(使用 plugins )。您还可以使用 this.style = { ... }
通过构造函数分配实例变量,并使用 this.style
在类中的任何位置访问它。
关于javascript - 在 React 类中添加存储在变量中的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42260533/