javascript - 您可以将有状态组件传递给在 componentDidMount() 中运行的函数吗?
问题描述
背景
我正在尝试将一个execute()
通过 props调用的componentDidMount()
函数传递给ChildComponent
. 该函数应该在 的上下文中ChildComponent
而不是在 的上下文中执行App
。例如,我希望能够this.props
从 props 的内部调用,但指的是and not() => {}
的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 单向数据流原理,但是可以这样解决:
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
. 希望它可以帮助你。
推荐阅读
- python - 根据行中值的百分位排名对数据框进行评分 - Python
- python - 在 Python 中集成 MySQL + Tkinter 的问题
- spring-boot - @Entry 没有硬编码的基础
- python - 根据 PEP8 字典中的长行
- python - python请求:请求期间出现SSL错误?
- c++ - std::string 和 int 的串联会导致转变。为什么?
- c# - 如何在c#中检查整数值是否为空
- c++ - 如何覆盖自定义 yocto 配方中任何 bbclass 设置的 LD_FLAGS?
- apache-spark - 如何利用 Parquet 分区在 Spark 中加载 RDD?
- nsis - 比较“已安装版本”与“待安装版本”