gpt4 book ai didi

javascript - 悬停在 MouseEnter 和 onMouseLeave React 上不起作用。超出最大调用堆栈大小

转载 作者:行者123 更新时间:2023-11-30 21:14:14 28 4
gpt4 key购买 nike

React 新手。当光标悬停在按钮上时,我正在尝试使用 React 为按钮实现颜色更改。当我在本地运行我的应用程序时,悬停似乎没有效果。有时我在加载应用程序时也会收到“超出最大调用堆栈大小”的 fatal error 。我相信我已经正确设置了代码,但显然,事实并非如此。任何帮助将不胜感激!

export class Header extends React.Component {
constructor(props) {
super(props)
this.state = {
hover: false
}
}

handleHover() {

this.setState({
hover: !this.state.hover
})
}

render(){

var buttonStyle = {

borderRadius: '5px',
borderColor: 'red',
marginTop: 25,

}


if(this.state.hover){

buttonStyle = {
backgroundColor: 'green',
color: 'yellow'
}
}
else{

buttonStyle = {
backgroundColor: 'blue',
color: 'orange'
}

}


}

return(
<button style={buttonStyle} onMouseEnter={this.handleHover()} onMouseLeave={this.handleHover()} type="button" className="btn btn-outline">Learn More</button>
)
}

最佳答案

您需要进行两项更改。首先在你的按钮元素中,你需要像这样传递你的 hove 处理函数(没有括号)

<button style={buttonStyle} onMouseEnter={this.handleHover} onMouseLeave={this.handleHover} type="button" className="btn btn-outline">Learn More</button>

并且您需要像这样将悬停处理函数绑定(bind)到构造函数中的类

constructor(props) {
super(props)
this.state = {
hover: false
}
this.handleHover = this.handleHover.bind(this)
}

关于javascript - 悬停在 MouseEnter 和 onMouseLeave React 上不起作用。超出最大调用堆栈大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45847805/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com