繁体   English   中英

React.js 如何正确实例化父组件中的子组件 class

[英]React.js how to properly instantiate child component in parent class

我对 react.js 很陌生,我一直在研究一个组件 class(子组件),它具有功能和一个 state object,我的最终目标是在父组件 class 中使用这个 class,这样它又可以调用它的功能并更新 state。

我遇到的问题是:

  1. 我不知道组件的生命周期,并且
  2. 我来自沉重的C#背景

意思是:我一直在对待这些组件类,就像对待任何 C# class 而不是 JavaScript 一样。我现在知道了。

但我需要帮助评估我的方法并解决这个我一直看到的问题:

在此处输入图像描述

这是我的孩子 Class 组件

import React, { Component } from 'react'; 从“axios”导入 axios;

export default class ClassB extends Component {
    constructor() {
        super();

        console.log("ClassB constructor got called");

        this.state = {
            users: [{ name: '', email: '' }]
        };
    }

    getUsers() {
        let URL = "https://localhost:5001/api/FooController/FooAction"
        let myParam = 100;

        axios.get(URL,
            {
                params: { myParam }
            })
            .then(response => {
                // handle logic here...

            }).catch(function (error) {
                console.log('What happened? ' + error.response.data);
            });
    }

    addUserData(name, email) {
        this.setState(this.state, { users: [name, email] });
    }

    componentDidMount() {
        console.log("ClassB componentDidMount got called");     
    }

    render() {
        console.log("ClassB render got called");
        return ( null )
    }
}

在我的父母 class (Home.js) 中,我正在实例化孩子 class (ClassB.js) 并使用它的实例:

import React, { Component } from 'react';
import ClassB from './ClassB'
import ClassC from './ClassC'

const classBComponent = new ClassB();

export class Home extends Component {
    static displayName = Home.name;
    

    constructor() {
        super();

    }

    componentDidMount() {
        this.timerID = setInterval(() => {
            classBComponent.getUserValues();
        }, 3000);
    }

    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    render() {

        myComponent.render();

        return (
            <div className="container">
                <h1>My Other Component:</h1>
                <div className="row">
                    <div className="col-sm">
                        <ClassC name={[{ component: classBComponent, info: ['John', 'john123@123.com'] }]} />
                    </div>
                </div>
            </div>
        );
    }
}

在这个父 class 中,我打算从 ClassB 组件调用“getUserValues() 方法。我还有另一个子组件 (ClassC),它是一个功能组件,我想传递实例化的 ClassB 组件,以便它可以访问其功能和状态。但是,在 ClassC 组件中,当我调用“addUserData()”方法时,它会给我上面粘贴的错误(见图)。

这是我设置 ClassC 的方式:

import React, { useEffect } from 'react';
import axios from 'axios';

const ClassC = (props) => {

    // variables
    let user  = props.name[0].info[0];
    let email = props.name[0].info[1];

    // component
    const component = props.name[0].component;


    // renders component
    function componentMount() {
        component.addSimModelNodeInfo(user, email);
    }

    // leaves the component
    function componentUnmount() {       

    }

    useEffect(() => {
        componentMount();
        return () => {
            componentUnmount();
        }
    }, [])

    return (
        <div className="card shadow-sm p-3 mb-5 bg-white rounded">
            <div className="card-header">
                <h5>{name}</h5>
                <h5>{email}</h5>
            </div>          
        </div>
    );
}

export default ClassC;

我之前提到过我对组件的生命周期没有扎实的了解。 我将那些 console.logs 放在 ClassB 中只是为了意识到唯一被调用的方法是构造函数。 componentDidMount() function 永远不会被调用,render() 也不会。 这是为什么? 我知道它与该错误有关,这就是为什么我的 ClassB 组件永远不会“安装”的原因。 我究竟做错了什么? 提前谢谢了。

下面是一个从子组件调用父组件 function 的例子。 为简洁起见,我使用功能组件,但这也完全有可能使用基于类的组件。

如果你对函数式组件不熟悉,你可以认为props就像this.props ,而 function 本身类似于类组件中的render()方法。 还有更多内容,但对于这个小示例,如果您需要翻译,它应该对您有所帮助。

const ChildComponent = (props) => <button onClick={props.onClick} />

const ParentComponent = () => {
  const onClick = () => {
    console.log("Click Clack");
  }
  return <ChildComponent onClick={onClick} />;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM