[英]On click trigger change of state on another component won't work
我设置了一个单击功能,该功能应该触发位于其他文件中的单独组件中的状态更改。 我的splash.js
文件包含Splash
组件,该组件具有一个徽标,单击该徽标时,它会从登录页面(Splash)更改为我的主页。 这是splash.js
:
import React, { Component } from 'react';
import Woods from './woods.jpeg';
import Logo1 from './whitestar.png';
import Logo2 from './orangestar.png';
export default class Splash extends Component {
constructor(props) {
super(props);
this.state = {
imgSrc: Logo1
//this.toggleShowHome = this.toggleShowHome.bind(this);
}
this.handleMouseOver = this.handleMouseOver.bind(this);
this.handleMouseOut = this.handleMouseOut.bind(this);
}
toggleShowHome(property){
this.setState((prevState)=>({[property]:!prevState[property]}));
//this.props.triggerClickOnLogo();
}
handleMouseOver() {
this.setState({
imgSrc: Logo2
});
}
handleMouseOut() {
this.setState({
imgSrc: Logo1
});
}
render() {
return(
<div id='Splashwrapper'>
<img id='logoc' onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} src={this.state.imgSrc} onClick={this.props.onLogoCLicked}></img>
<img id='backg' src={Woods}></img>
</div>
);
}
}
单击功能应更改App.js
文件中splash
的状态:
import React, { Component } from 'react';
import Splash from './splash';
import Menu from 'components/Global/Menu';
export default class About extends Component {
constructor(){
super();
this.state = {
splash: true
}
this.logoClicked = this.logoClicked.bind(this);
}
//componentDidMount() {
//setTimeout (() => {
//this.setState({splash: false});
//}, 10000);
//}
logoClicked(props) {
this.setState({splash:false});
}
render() {
if (this.state.splash) {
return <Splash onLogoClicked={this.logoClicked.bind(this)} />
}
const { children } = this.props; // eslint-disable-line
return (
<div className='About'>
<Menu />
{ children }
</div>
);
}
}
但是,我的代码没有任何作用。 如何在Splash
链接on click函数以更改App.js
文件中的splash
状态,使其显示我的主页?
看起来您的Splash
组件中有一个错字。 在img
您执行onClick={this.props.onLogoCLicked}
但是当您使用组件时, onLogoClicked
传递道具-注意单击的大写onLogoClicked
L。
考虑在组件中使用propTypes
,如果没有所需的prop,React会对此发出一些噪音。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.