【发布时间】:2019-08-26 10:38:48
【问题描述】:
我有 2 个组件,第一个组件有一个在第二个组件的异步函数之后调用的函数,我想做的是类似于 vue 的 this.$emit() 函数,它随时从该组件调用一个监听器,我该怎么做这样做有反应吗?
这是我的第一个组件
import React, { Component } from 'react';
import SecondComponent from '../Path/to/second/component'
class MainMenu extends Component {
callThis (data) {
console.log(data)
}
render () {
return <SecondComponent onDataReceived = {this.callThis} />
}
}
export default FirstComponent
这是我的第二个组件
import React, { Component } from 'react';
class SecondComponent extends Component {
async asyncFunction () {
const data = await getDataFromApi()
// call the function from first component here...
}
render () {
return <button onClick={() => this.asyncFuncion} />
}
}
export default FirstComponent
【问题讨论】:
-
第二个组件的 onClick 没有执行 asyncFunction;要么写 onClick={this.asyncFunction} 要么 onClick={()=>this.asyncFunction()} 在你的 asyncFunction 里面调用 this.props.onDataReceived( );
标签: javascript reactjs function asynchronous