繁体   English   中英

单击时触发另一个组件上的状态更改将不起作用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM