简体   繁体   English

在ReactJS中状态更改后,内嵌样式无法正确呈现

[英]In-line Styles not rendering properly after state change in ReactJS

I am trying to apply a simple state change to a button in React. 我正在尝试将简单的状态更改应用于React中的按钮。

'use strict';
class ReactButton extends React.Component {

  constructor(props) {
    super(props);
    this.state = {hovering: false};
  }

  onClick() {
    this.props.handleClick(this.props.text);
  }

  onHover() {
    this.setState({
        hovering: !this.state.hovering
    });
  }

  render() {
    const color = this.state.hovering ? 'blue' : 'default';
    const text = this.state.hovering ? 'Hover Text' : this.props.text;
    console.log(color, text);
    return (
        <button
            onClick={this.onClick.bind(this)}
            style={{color: color}}
            onMouseEnter={this.onHover.bind(this)}
            onMouseOut={this.onHover.bind(this)}>
                {text}
        </button>
    );
  }
}

ReactDOM.render(
  <ReactButton 
    text={"Original Text"}
    handleClick={(e) => console.log('clicked')} />,
  document.querySelector('#container')
);

If you take a look at the demo you will notice that the text color changes to blue when the button is hovered, however when the mouse leaves the button the text color remains blue. 如果您看一下演示,您会注意到当鼠标悬停在按钮上时,文本颜色变为蓝色,但是当鼠标离开按钮时,文本颜色仍然为蓝色。 The event is fired and the state does change triggering a re-render as evidenced by the text changing. 事件触发,状态发生变化,触发重新渲染,如文本更改所证明。

Why is react not updating the in-line style? 为什么反应不更新嵌入式样式? What can I do to fix this? 我该怎么做才能解决此问题?

color: does not have default option, color:没有default选项,

change default to inherit (or default color name what you want like #000000 ), 更改defaultinherit (或使用默认颜色名称#000000 ),

const color = this.state.hovering ? 'blue' : 'inherit';

Example

Example-2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM