简体   繁体   English

如何在反应中从一个组件调用 function 到另一个组件

[英]how to call function from one component to another component in react

i am working on 2 components, one is Game and second it PickWinner , Game is my parent component, from this component i want to call PickWinner component pickWinner function, from Game component startPickWinnerCardTimer function, can anyone please help me how to do that, here i have put my both component, any help will be really appreciated.我正在研究 2 个组件,一个是Game ,第二个是PickWinner ,Game 是我的父组件,我想从这个组件调用PickWinner组件pickWinner function,从Game组件startPickWinnerCardTimer function,谁能帮我怎么做我已经把我的两个组件,任何帮助将不胜感激。

Game.tsx游戏.tsx

import {PickWinner} from "@Areas/Game/Components/Gameplay/PickWinner";

class Game extends React.Component<RouteComponentProps<IGameParams>, IGameState>
{
    private supportDelayTimeout = 0;
    public interval;
    public interval_show_winner_counter;
    public can_we_update=0;
    public number_seconds=30;

    constructor(props: RouteComponentProps<IGameParams>) {
        super(props);

        this.state = {
            socketData: SocketDataStore.state,
            gameData: GameDataStore.state,
            userData: UserDataStore.state,
            restartLoading: false,
            restartDelayed: true,
            showSupport: false,
            chatDrawerOpen: true,
            isFirstTime: false,
            total: this.number_seconds,
            showTimer: false,
            displayTimer : '00:30',
        };
    }

    public startPickWinnerCardTimer = (winnerGuid) => {
        this.interval_show_winner_counter = setInterval(function (winnerGuid) {
            let timer =  120, minutes, seconds;
            if(typeof timer!==undefined && timer!=null) {
                minutes = parseInt(timer/60 as any,10);
                seconds = parseInt(timer%60 as any,10);
                minutes = minutes < 10 ? "0" + minutes : minutes;
                seconds = seconds < 10 ? "0" + seconds : seconds;
                
                console.log("show winner timer");
                console.log(minutes + ":" + seconds);

                this.setState({displayTimer:minutes + ":" + seconds})
                
                
                if (--timer < 0) {
                    pickWinner(winnerGuid);
                    this.setState({total:this.number_seconds,showTimer:false});
                    clearInterval(this.interval_show_winner_counter);
                    return false;
                } 
            }
        }, 1000);
    }

    private getWinnerFromState(state: IGameState) {
        const {
            players,
            settings
        } = state.gameData.game ?? {};

        const playerGuids = Object.keys(players ?? {});
        const roundsToWin = getTrueRoundsToWin(state.gameData.game as ClientGameItem);
        const winnerGuid = playerGuids.find(pg => (players?.[pg].wins ?? 0) >= roundsToWin);
        return winnerGuid;
    }
};

export default withRouter(Game);

PickWinner.tsx PickWinner.tsx

import Grid from "@material-ui/core/Grid";
import Divider from "@material-ui/core/Divider";
import * as React from "react";
import {useState} from "react";
import {useDataStore} from "../../../../Global/Utils/HookUtils";
import {GameDataStore} from "../../../../Global/DataStore/GameDataStore";
import {WhiteCard} from "../../../../UI/WhiteCard";
import {UserDataStore} from "../../../../Global/DataStore/UserDataStore";
import sanitize from "sanitize-html";
import {LoadingButton} from "../../../../UI/LoadingButton";
import {CardId} from "../../../../Global/Platform/Contract";
import {cardDefsLoaded} from "../../../../Global/Utils/GameUtils";

export interface IPickWinnerProps
{
    children?: undefined;
    canPick: boolean;
    timeToPick: boolean;
    revealMode: boolean;
    hasWinner: boolean;
    onPickWinner?: (winnerGuid: string) => Promise<any>;
}



export const PickWinner: React.FC<IPickWinnerProps> = (

    {
        onPickWinner,
        canPick,
        timeToPick,
        hasWinner,
        revealMode
    }

) =>
{

    let interval_show_winner_counter;
    this.props.func(this, 1234);

    const gameData = useDataStore(GameDataStore);
    const userData = useDataStore(UserDataStore);
    const [pickWinnerLoading, setPickWinnerLoading] = useState(false);
    const [updateShowWinnerTimer,setUpdateShowWinnerTimer] = useState('02:00');

    const me = gameData.game?.players?.[userData.playerGuid] ?? gameData.game?.spectators?.[userData.playerGuid];

    const defsLoaded = cardDefsLoaded(gameData);

    if (!me || !gameData.game || !defsLoaded)
    {
        return null;
    }

    const pickWinner = (winnerGuid: string) =>
    {
        if (onPickWinner)
        {
            setPickWinnerLoading(true);

            onPickWinner(winnerGuid)
                .finally(() => setPickWinnerLoading(false));
        }
    };

}

This is generally not the way to go about things in React.这通常不是 go 关于 React 中的事情的方式。 Usually what you want to do is pass down functionality to children in props, and pass up notifications from children in events.通常你想要做的是将功能传递给 props 中的子项,并在事件中传递子项的通知。

you can use forwardRef for this issue.你可以使用forwardRef来解决这个问题。 Try this试试这个

Also you want to pass any functionality or notification from child, you should use Redux to notify anything to parent component.此外,您想从子组件传递任何功能或通知,您应该使用Redux向父组件通知任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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