React-内联动态组件样式未更新onMouseOver和onMouseOut事件

时间:2018-12-13 01:10:03

标签: javascript reactjs

在我的应用中执行以下代码时,该按钮具有白色背景,将鼠标悬停在其上方不会更改任何内容。但是,控制台日志确实显示onMouseOver和onMouseOut事件正在触发,并将initialState的值从false更改为true,然后再次更改。

rnd = random.randint(1,5)

if rnd == 1:
    # stuff here
if rnd == 2:
    # stuff here
const GetQuoteButton = (props) => {

	let initialState = false;

	function onMouseOver() {
		return initialState = true;
	}

	function onMouseOut() {
		return initialState = false;
	}

	return (
		<button
			onMouseOver={onMouseOver}
			onMouseOut={onMouseOut}
			style={{ backgroundColor: initialState ? props.color : 'white' }}
			onClick={props.changeQuote}
			className="GetQuoteButton">
			Change Quote
		</button>
	)

}

ReactDOM.render(<GetQuoteButton color="red" />, document.getElementById('root'))

2 个答案:

答案 0 :(得分:3)

您正在使用功能组件。它对状态一无所知。仅当道具更改时才重新渲染您的组件。当initialState更改时,React无法知道您的组件需要重新渲染。

要解决此问题,您需要使用带有状态的类:

class GetQuoteButton extends React.Component {
      constructor(props) {
        super(props);
        this.state = { hover: false };
      }
    
      onMouseOver() {
        this.setState({ hover: true });
      }
    
      onMouseOut() {
        this.setState({ hover: false });
      }
    
      render() {
        return (
          <button
            onMouseOver={() => this.onMouseOver()}
            onMouseOut={() => this.onMouseOut()}
            style={{ backgroundColor: this.state.hover ? this.props.color : "white" }}
            onClick={this.props.changeQuote}
            className="GetQuoteButton"
          >
            Change Quote
          </button>
        );
      }
    }

ReactDOM.render(<GetQuoteButton color="red" />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

答案 1 :(得分:0)

发生了什么事?

1°您的onMouseEvents只是在更改变量,而react不知道需要使用此变量更新来重新渲染。

2°您正在使用无状态组件,这里有两个选项:     要么将此组件更改为一种状态,要么将初始状态更改为来自props,然后对父组件执行setState

示例应起作用: 进行setState更改变量状态/值将强制重新渲染此组件,并使用更改后的变量更新ui

import React from 'react';

class GetQuoteButton extends React.Component {

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

onMouseOver=()=> {
    this.setState({initialState:true})
}

onMouseOut =()=>{
    this.setState({initialState:false})
}

render() {
    const {initialState}=this.state
    const {color,changeQuote}=this.props

    return <button
			onMouseOver={this.onMouseOver}
			onMouseOut={this.onMouseOut}
			style={{ backgroundColor: initialState ? 
                     color : 'white' }}
			onClick={changeQuote}
			className="GetQuoteButton">
			Change Quote
		</button>
}
}
 
export default GetQuoteButton