子组件调用父组件的功能

时间:2019-08-18 17:42:50

标签: javascript reactjs

我有两个部分,我给父母部分作为我孩子部分的道具,我想在我的孩子部分中调用父母功能。

父母部分:

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。所以我把我的部分作为道具。 我的子组件将类作为道具接收,所以为什么我不能调用像this.props.nameOfFunction();

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

2 个答案:

答案 0 :(得分:1)

当前您没有将任何函数prop传递给const myworker = new Worker('worker.js'); function checkZipCode() { event.preventDefault(); let zipcode = document.getElementById('zipcode'); myworker.postMessage(zipcode.value); console.log('Message posted to worker') }; // Worker.js file addEventListener('message', (e) => { console.log(e) })

<SimplePopover />

假设要通过<SimplePopover response={this}/>

changeRoute

像这样修改SimplePopover:

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

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

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

例如。

答案 1 :(得分:0)

通过传递这意味着我们正在将整个父组件方法传递给子组件,即所有写入/变量的方法都传递给子组件。

<SimplePopover response={this}/>

因此,使用上述代码,我们可以将父方法称为props.response.changeRoute(event)

还有另一种方法

<SimplePopover {...this}/>

使用上述代码,您可以将父方法调用为props.changeRoute(event)