gpt4 book ai didi

javascript - 您可以向有状态组件传递一个在 componentDidMount() 内部运行的函数吗?

转载 作者:行者123 更新时间:2023-11-28 03:07:53 24 4
gpt4 key购买 nike

背景

我试图通过 props 将一个名为 execute() 的函数传递给 ChildComponent 内部的 componentDidMount() 函数。该函数应在 ChildComponent 上下文中执行,而不是在 App 上下文中执行。例如,我希望能够从 execute 属性的 () => {} 内部调用 this.props,但是 this.props 指的是 ChildComponent 的 props,而不是 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;

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

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 中> 您将能够像在 ChildComponent 中一样访问 this.props。希望对您有帮助。

关于javascript - 您可以向有状态组件传递一个在 componentDidMount() 内部运行的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60442678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com