当子组件有嵌套的多个父组件时,从子组件调用超父函数

Calling to super parent function from child component when it has nested multiple parents

本文关键字:组件 函数 调用 嵌套      更新时间:2023-09-26

让我们假设一个React组件有多个父组件。当我想调用父级组件(最高级组件)的函数时。我怎么能做到呢?请参阅示例代码。

' ' '

export default class WeekView extends React.Component {      
    constructor(props) {
        super(props);
    }
    // this functions has to be called from third child
    loadData() {
        var data = [];
        this.setState({events : data});
    }
    render() {
        return (
            <ChildOne >
        );
    }
}
export class ChildOne extends React.Component {
    constructor(props) {
        super(props);
    } 
    render() {
        return (
            <ChildTwo />
        );
    }
}
export class ChildTwo extends React.Component {
    constructor(props) {
        super(props);
    } 
    render() {
        return(
            <ChildThree />
        );
    }
}
export class ChildThree extends React.Component {
    constructor(props) {
        super(props);
    }
    addEvent() {
        // how to call loadData() function, which is included in the highest parent
    }
    render() {
        return(
            <Button onCLick={this.addEvent.bind(this)} />
        );
    }
}

' ' '

是的。我们可以通过props将请求发送到层次结构的顶端。但是有没有别的方法可以用别的方法来做,除非通过层次结构。提前谢谢你。

反应的方式是从父组件通过props向下传递功能。你说这是你的答复。

基本上你的父级会有一个函数传递给子级然后触发它