ReactJS中的状态更改后,内联样式未正确呈现

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

本文关键字:样式 状态 ReactJS      更新时间:2023-09-26

我正在尝试对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')
);

如果你看一下演示,你会注意到当鼠标悬停在按钮上时,文本颜色会变为蓝色,但当鼠标离开按钮时,文本的颜色仍然是蓝色。事件被触发,并且状态确实发生了更改,从而触发了重新渲染,文本更改就是明证。

为什么react不更新内嵌样式?我能做些什么来解决这个问题?

color:没有default选项,

default更改为inherit(或您想要的默认颜色名称,如#000000),

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

Example

Example-2