背景

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

这可能吗?



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;

最佳答案

这违反了react unidirectional data flow principle,但是您可以通过以下方式解决它:

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;


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

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。希望对您有帮助。

08-04 10:36