Javascript ReactJS中的内联样式

Javascript ReactJS中的内联样式,javascript,css,reactjs,Javascript,Css,Reactjs,我是新手。我试图在点击按钮时同时改变按钮的文字和颜色。此代码适用于: class ToggleHelp extends React.Component { constructor(props) { super(props); this.state = {isHelpOn: true}; // This binding is necessary to make `this` work in the callback this.handleClick = thi

我是新手。我试图在点击按钮时同时改变按钮的文字和颜色。此代码适用于:

class ToggleHelp extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isHelpOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isHelpOn: !prevState.isHelpOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <ToggleHelp />,
  document.getElementById('root')
);
类切换帮助扩展React.Component{
建造师(道具){
超级(道具);
this.state={isHelpOn:true};
//此绑定是使`This`在回调中工作所必需的
this.handleClick=this.handleClick.bind(this);
}
handleClick(){
this.setState(prevState=>({
isHelpOn:!prevState.isHelpOn
}));
}
render(){
返回(
{this.state.isHelpOn?'HELP ON':'HELP OFF'}
);
}
}
ReactDOM.render(
,
document.getElementById('root'))
);
但是,当我尝试使用如下所示的内联样式时,代码停止工作

<button style={background:yellow} onClick={this.handleClick}>
  {this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
</button>

{this.state.isHelpOn?'HELP ON':'HELP OFF'}

我试过好几次了,用不同的方法做。目前我希望它是一种内联样式。是否可以直接从React应用内联样式?如果是,则想法是评估状态并通过条件语句将一种颜色设置为另一种颜色。

将内联样式声明为对象:

<button style={{ background: 'yellow' }} onClick={this.handleClick}>
  {this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
</button>

{this.state.isHelpOn?'HELP ON':'HELP OFF'}

缺少一组括号和一些引号:

<button style={{background: 'yellow'}} onClick={this.handleClick}>
  {this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
</button>

{this.state.isHelpOn?'HELP ON':'HELP OFF'}

React的style prop需要一个对象(
{background:'yellow'}
),因为它不是一个简单的字符串,所以需要在prop的周围加上一组括号

<button style={{background:'yellow'}} onClick={this.handleClick}>
  {this.state.isHelpOn ? 'HELP ON' : 'HELP OFF'}
</button>

{this.state.isHelpOn?'HELP ON':'HELP OFF'}

外部的
{}
s只告诉JSX编译器内部是JavaScript代码。
{}
s的内部集合创建一个JavaScript对象文本。

首先,样式必须作为对象传递

其次-css值必须是字符串

style={{ background: 'yellow' }}

这样写:
style={{{backgroundColor:'yellow'}}