背景
我正在尝试通过道具将名为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
。希望对您有帮助。