передача свойств дочернему функциональному компоненту - PullRequest
1 голос
/ 05 мая 2020

Я пытаюсь передать переменную аутентификации и функцию для переключения true и false, чтобы я мог контролировать, что отображается для пользователя в соответствии с его статусом, является ли он авторизованным или нет я думаю, что все в порядке ... также тот же код, который я использую для компонента класса, и он работает, и я могу console.log(props) быть стороной функции рендеринга ... я думаю, что мне не хватает чего-то здесь в этом функциональном компоненте ... мне нужен другой глаза, чтобы посмотреть на это и сказать мне, где я go неправильно

loginButtons.js:10 Uncaught TypeError: Cannot read property 'props' of undefined
    at onClick (loginButtons.js:10)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:306)
    at executeDispatch (react-dom.development.js:389)
    at executeDispatchesInOrder (react-dom.development.js:414)
    at executeDispatchesAndRelease (react-dom.development.js:3278)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:3287)
    at forEachAccumulated (react-dom.development.js:3259)
    at runEventsInBatch (react-dom.development.js:3304)
    at runExtractedPluginEventsInBatch (react-dom.development.js:3514)
    at handleTopLevel (react-dom.development.js:3558)
    at batchedEventUpdates$1 (react-dom.development.js:21871)
    at batchedEventUpdates (react-dom.development.js:795)
    at dispatchEventForLegacyPluginEventSystem (react-dom.development.js:3568)
    at attemptToDispatchEvent (react-dom.development.js:4267)
    at dispatchEvent (react-dom.development.js:4189)
    at unstable_runWithPriority (scheduler.development.js:653)
    at runWithPriority$1 (react-dom.development.js:11039)
    at discreteUpdates$1 (react-dom.development.js:21887)
    at discreteUpdates (react-dom.development.js:806)
    at dispatchDiscreteEvent (react-dom.development.js:4168)

Вот мой дом. js

import React, { Component } from "react";

import { GoogleLoginButton } from "./loginButtons";
import MenuBarApp from "./menuBarApp";

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            auth: true,
        };
    }

    authStatus(status) {
        this.setState({ auth: status });
    }

    render() {
        const { auth } = this.state;
        return (
            <div>
                {auth ? (
                    <MenuBarApp auth={this.state.auth} authStatus={this.authStatus.bind(this)} />
                ) : (
                    <GoogleLoginButton auth={this.state.auth} authStatus={this.authStatus.bind(this)} />
                )}
            </div>
        );
    }
}

export default Home;


, а это loginButtons. js

import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";

export function GoogleLoginButton(props) {
    const classes = useStyles();

    return (
        <div className={classes.root}>
            <Button variant="contained" size="large" color="primary" onClick={() => this.props.authStatus(true)}>
                Login with your Google Account
            </Button>
        </div>
    );
}

const useStyles = makeStyles((theme) => ({
    root: {
        "& > *": {
            margin: theme.spacing(1),
        },
    },
}));

Ответы [ 2 ]

3 голосов
/ 05 мая 2020

Вам не обязательно использовать this.props в функциональном компоненте, props доступны как параметр функции.

Только в компонентах class, к реквизитам обращаются как this.props.

export function GoogleLoginButton(props) {
    const classes = useStyles();

    return (
        <div className={classes.root}>
            <Button variant="contained" size="large" color="primary" onClick={() => props.authStatus(true)}>
                Login with your Google Account
            </Button>
        </div>
    );
}
0 голосов
/ 05 мая 2020

Измените this.props.authStatus(true)} на props.authStatus(true)} в loginButton. js, потому что это функциональный компонент, а не компонент на основе классов.

export function GoogleLoginButton({authStatus}) {
const classes = useStyles();
    return (
            <div className={classes.root}>
                <Button variant="contained" size="large" color="primary" 
                 onClick={() => authStatus(true)}>
                    Login with your Google Account
                </Button>
            </div>
        );
  }

Вы можете использовать деструктурирование.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...