Ваша проблема e.target
, это не всегда тот элемент, который связан с этим событием. В этом случае вы должны использовать currentTarget
, это всегда тот элемент, который связан с событием, даже если событие находится на дочернем элементе.
Измените это на:
function changeBackground(e) {
e.currentTarget.style.backgroundColor = "#ff6f00";
e.currentTarget.style.color = "#ffffff";
}
function resetBackground(e){
e.currentTarget.style.backgroundColor = "#ffffff";
e.currentTarget.style.color = "#616161";
}
, и я бы посоветовал вам поместить функции в качестве метода для проверки класса ниже:
class InfoBlogs extends React.Component{
constructor(props){
super(props);
this.changeBackground = this.changeBackground.bind(this);
this.resetBackground = this.resetBackground.bind(this);
}
changeBackground(e) {
e.currentTarget.style.backgroundColor = "#ff6f00";
e.currentTarget.style.color = "#ffffff";
}
resetBackground(e){
e.currentTarget.style.backgroundColor = "#ffffff";
e.currentTarget.style.color = "#616161";
}
render(){
return(
<div id="parent" style={ styles.parentCard }
onMouseOver={this.changeBackground}
onMouseLeave={this.resetBackground}>
...
</div>);
}
}
Или Вы можете использовать React.createRef()
для лучшего использования:
class InfoBlogs extends React.Component{
constructor(props){
super(props);
this.parentRef = React.createRef();
this.changeBackground = this.changeBackground.bind(this);
this.resetBackground = this.resetBackground.bind(this);
}
changeBackground(e) {
this.parentRef.current.style.backgroundColor = "#ff6f00";
this.parentRef.current.style.color = "#ffffff";
}
resetBackground(e){
this.parentRef.current.style.backgroundColor = "#ffffff";
this.parentRef.current.style.color = "#616161";
}
render(){
return(
<div id="parent" ref={this.parentRef} style={ styles.parentCard }
onMouseOver={this.changeBackground}
onMouseLeave={this.resetBackground}>
...
</div>);
}
}