javascript - 子组件调用父组件函数

标签 javascript reactjs

我有两个组件,我将 parent 组件作为子组件的 Prop ,并且我想在子组件中调用 parent 函数。

父组件:

import React, {Component} from 'react';
import "../../css/App.css"
import "../../css/Admin.css"
import { connect } from 'react-redux'
import {withRouter} from 'react-router-dom'
import Switch from '@material-ui/core/Switch';
import AuthentificationService from "../../api/AuthentificationService"
import SimplePopover from "./AddUser"
import Users from "./Users"
import Cookies from 'universal-cookie';
import ModalAdd from "../Modal/ModalAdd";

const cookies = new Cookies();

class Admin extends Component {
    constructor() {
        super();

        this.state = {
            response: [{admin: false, createdAt: "", email: "", form_filled: false, id: "", updateAt: "", username: "", verified: false}],
            addUserWorks: false
        };

        this.changeRoute = this.changeRoute.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.setCookie = this.setCookie.bind(this);
        this.setDefaultUserWorks = this.setDefaultUserWorks.bind(this);
        this.setUserWorks = this.setUserWorks.bind(this);
    }

    setDefaultUserWorks(e) {
        console.log("setDefaultUserWorks")
        this.setState({
            addUserWorks: false
        });
    }

    setUserWorks(e) {
        console.log("setUserWorks")

    }

    setCookie(e) {
        cookies.set('access_token', this.props.access_token);
        console.log(cookies.get('access_token'));
    }

    /// Change route
    changeRoute(e) {
        this.props.history.push(e)
    }

    handleChange(e) {

    };

    /// Submit the forms
    async handleSubmit() {
        try {
            await AuthentificationService.getAllUsers({

            })  .then((data) => {
                console.log(data);
                this.setState({
                    response: data
                });
            })
        } catch (error) {
            alert("NO")
        }
    }

    render() {

        this.setCookie();
        var i = 0;
        const nameList = this.state.response.map(name => {
            return (
                <ul>
                    <li className="test">{this.state.response[i].email} </li>
                    <li className="test" >
                        <Switch
                        checked={this.state.response[i].admin}
                        value="checkedVerified"
                        inputProps={{ 'aria-label': 'secondary checkbox' }}
                        />
                    </li>
                    <li className="test" >
                        <Switch
                            checked={this.state.response[i].verified}
                            value="checkedVerified"
                            inputProps={{ 'aria-label': 'secondary checkbox' }}
                        />
                    </li>
                    <li className="test" >
                        <Switch
                            checked={this.state.response[i++].form_filled}
                            value="checkedVerified"
                            inputProps={{ 'aria-label': 'secondary checkbox' }}
                        />
                    </li>
                </ul>
            )
        })

        return (
            <div>
                <div>
                    {this.state.addUserWorks === false ?  "" : <ModalAdd parentMethod={this.setDefaultUserWorks} title="Ajout d'un utilisatuer" message="Vous alvez ajouté un utilisateur"/>}
                </div>
                <button className="button"  onClick={() => {
                    this.handleSubmit();
                }}>
                    Get/refresh the users list
                </button>
                <Users response={this.state.response}/>
                <SimplePopover response={this}/>
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        access_token: state.access_token,
        refresh_token: state.refresh_token,
        user_id: state.user_id,
        username: state.username,
        email: state.email,
        admin: state.admin,
    }
}

export default withRouter(connect(mapStateToProps)(Admin))

我的子组件是 SimplePopover。所以我把我的组件作为 Prop 。 我的子组件接收类作为 props 那么为什么我不能调用像 this.props.nameOfFunction(); 这样的函数

编辑:我有这个错误:props.setUserWorks 不是函数

最佳答案

目前您没有将任何函数属性传递给 <SimplePopover /> :

<SimplePopover response={this}/>

假设想要通过 changeRoute :

 /// Change route
    changeRoute(e) {
        this.props.history.push(e)
    }

像这样修改SimplePopover:

<SimplePopover response={this} changeRoute={this.changeRoute}/>

然后将其绑定(bind)到组件本身并通过访问 prop 来使用它:

<button onClick={(event)=>{props.changeRoute(event)}}

例如。

关于javascript - 子组件调用父组件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57546953/

相关文章:

JavaScript 函数中的 PHP 变量

javascript - gulp + browserify + reactjs,未捕获的 ReferenceError : React is not defined

angularjs - 如果有简单的方法,为什么我们需要reactjs-bootstrap?

javascript - 在 html 表单中显示占位符而不是默认值

javascript - 谷歌云功能::无法使用 'require'语句

javascript - 谷歌浏览器中的跨域设置

reactjs - 我如何在 React 中解决 "_this is undefined"?

javascript - 使用AJAX定时器获取 "PHP URL Content"

javascript - 如何在另一个类中模拟异步函数调用

node.js - React Native bundle 错误 : Module `scheduler` does not exist in the Haste module map