首页 > 解决方案 > 您可以将有状态组件传递给在 componentDidMount() 中运行的函数吗?

问题描述

背景

我正在尝试将一个execute()通过 props调用的componentDidMount()函数传递给ChildComponent. 该函数应该在 的上下文中ChildComponent而不是在 的上下文中执行App。例如,我希望能够this.props从 props 的内部调用,但指的是and not() => {}的props 。executethis.propsChildComponentApp

这可能吗?

例子

App.js

import React from 'react';

import ChildComponent from './ChildComponent';

const App = () => (
    <>
      <ChildComponent
          execute={() => {console.log('Hello, World.');}}
      />
    </>
);

export default App;

ChildComponent.js

import React from 'react';

class ChildComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {};
    }

    componentDidMount() {
        this.props.execute();
    }

    render() {
        return (
            <>
                <h1>Hello, World.</h1>
            </>
        );
    }
}

export default ChildComponent;

标签: javascriptreactjs

解决方案


这违反了react 单向数据流原理,但是可以这样解决:

import React from 'react';

class ChildComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {};
    }

    componentDidMount() {
        return this.props.length > 0 ? this.props.execute.bind(this)() : '';
    }

    render() {
        return (
            <>
                <h1>Hello, World.</h1>
            </>
        );
    }
}

export default ChildComponent;

在父组件中,您必须将箭头函数更改为普通函数语法:

import React from 'react';

import ChildComponent from './ChildComponent';

const App = () => (
    <>
      <ChildComponent
          execute={function() {console.log(this.props);}}
      />
    </>
);

export default App;

现在,在execute范围内,this将引用ChildComponent实例,因此execute function您将能够this.props像在ChildComponent. 希望它可以帮助你。


推荐阅读