首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >子组件调用父组件的组件函数

子组件调用父组件的组件函数
EN

Stack Overflow用户
提问于 2019-08-19 01:42:51
回答 2查看 75关注 0票数 0

我有两个组件,我给我的parents组件作为我的子组件的道具,我想在我的子组件中调用parents函数。

父组件:

代码语言:javascript
复制
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不是一个函数

EN

回答 2

Stack Overflow用户

发布于 2019-08-19 01:52:32

当前您没有向<SimplePopover />传递任何函数属性

代码语言:javascript
复制
<SimplePopover response={this}/>

比方说想要通过changeRoute

代码语言:javascript
复制
 /// Change route
    changeRoute(e) {
        this.props.history.push(e)
    }

按如下方式修改SimplePopover:

代码语言:javascript
复制
<SimplePopover response={this} changeRoute={this.changeRoute}/>

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

代码语言:javascript
复制
<button onClick={(event)=>{props.changeRoute(event)}}

例如。

票数 1
EN

Stack Overflow用户

发布于 2019-08-19 02:08:17

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

<SimplePopover response={this}/>

因此,使用上面的代码,我们可以调用父方法作为props.response.changeRoute(event)

有另一种方法可以做到这一点。

<SimplePopover {...this}/>

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57546953

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档