使用 React 为对象 属性 设置样式
Styling an objects property using React
如何更改 React 组件的样式?
这将在背景颜色上出错,但删除后它将输出 'hello'
我想在反应对象中基于 属性 设置样式。
if(this.state.msg[0].msg.author.name == 'Rich){
background-color: red;
console.log('hello')
};
在 React 中,我们在指定所需的 CSS 样式名称时使用驼峰命名法。
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
https://facebook.github.io/react/tips/inline-styles.html
这是一个演示,说明如何根据状态中保存的值有条件地应用样式:http://codepen.io/PiotrBerebecki/pen/xEyqER
class App extends React.Component {
constructor() {
super();
this.state = {
msg: [
{msg: {author: {name: 'Rich'}}},
{msg: {author: {name: 'John'}}},
{msg: {author: {name: 'Pete'}}}
]
};
}
render() {
const style1 = {
backgroundColor: 'red'
};
const style2 = {
backgroundColor: 'blue'
};
const style3 = {
backgroundColor: 'gray'
};
const getStyleName = (name) => {
switch (name) {
case 'Rich':
return style1;
case 'John':
return style2;
default:
return style3;
}
};
const renderNames = this.state.msg.map((item, index) => {
return (
<p key={index} style={getStyleName(item.msg.author.name)}>
{item.msg.author.name}
</p>
);
})
return (
<div>
<h1>React</h1>
{renderNames}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
如何更改 React 组件的样式? 这将在背景颜色上出错,但删除后它将输出 'hello' 我想在反应对象中基于 属性 设置样式。
if(this.state.msg[0].msg.author.name == 'Rich){
background-color: red;
console.log('hello')
};
在 React 中,我们在指定所需的 CSS 样式名称时使用驼峰命名法。
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 https://facebook.github.io/react/tips/inline-styles.html
这是一个演示,说明如何根据状态中保存的值有条件地应用样式:http://codepen.io/PiotrBerebecki/pen/xEyqER
class App extends React.Component {
constructor() {
super();
this.state = {
msg: [
{msg: {author: {name: 'Rich'}}},
{msg: {author: {name: 'John'}}},
{msg: {author: {name: 'Pete'}}}
]
};
}
render() {
const style1 = {
backgroundColor: 'red'
};
const style2 = {
backgroundColor: 'blue'
};
const style3 = {
backgroundColor: 'gray'
};
const getStyleName = (name) => {
switch (name) {
case 'Rich':
return style1;
case 'John':
return style2;
default:
return style3;
}
};
const renderNames = this.state.msg.map((item, index) => {
return (
<p key={index} style={getStyleName(item.msg.author.name)}>
{item.msg.author.name}
</p>
);
})
return (
<div>
<h1>React</h1>
{renderNames}
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);