【问题标题】:Child component call parent's component function子组件调用父组件函数
【发布时间】:2019-08-18 17:42:50
【问题描述】:

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

父组件:

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 不是函数

【问题讨论】:

  • 通常我会将回调函数传递给子组件而不是父组件。像&lt;SimplePopover parentFunction={this.theFunction} /&gt; 这样的东西在子组件中做this.props.parentFunction()
  • 你没有将任何函数属性传递给&lt;SimplePopover /&gt;
  • 但是如果我给“this”那么这意味着我给状态和功能没有?

标签: javascript reactjs


【解决方案1】:

目前您没有将任何函数道具传递给&lt;SimplePopover /&gt;

<SimplePopover response={this}/>

假设要通过changeRoute

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

像这样修改 SimplePopover:

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

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

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

例如。

【讨论】:

    【解决方案2】:

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

    &lt;SimplePopover response={this}/&gt;

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

    还有另一种方法

    &lt;SimplePopover {...this}/&gt;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2020-03-25
      • 1970-01-01
      • 2019-11-27
      • 2018-07-01
      • 1970-01-01
      相关资源
      最近更新 更多