当单击一个元素时,我试图从另一个组件中调用一个函数。我从文件导入了该函数,但是它不起作用。我可以通过这种方式从另一个组件调用该函数,还是需要使用其他方法?
1.js
import React, { Component } from 'react';
export default class extends Component {
render() {
return (
<div className={cn()}>
<div onClick={onDownloadFile }>
<UploadFile />
</div>
);
}
}
2.js
import React, { Component } from 'react';
import UploadForm, { onDownloadFile } from '1.js'
export default class extends Component {
onDownloadFile = () => {
...
}
render() {
return (
<div>
<UploadForm />
</div>
);
}
}
答案 0 :(得分:0)
如果我正确理解,UploadForm
是1.js和2.js中子组件的默认导出。您想将onDownloadFile
作为回调道具传递给UploadForm
。
1.js
import React, { Component } from 'react';
export default class extends Component {
render() {
return (
<div className={cn()}>
<div onClick={this.props.onDownloadFile }> // <-- access via props
<UploadFile />
</div>
</div>
);
}
}
2.js
import React, { Component } from 'react';
import UploadForm from '1.js';
export default class extends Component {
onDownloadFile = () => {
...
}
render() {
return (
<div>
<UploadForm onDownloadFile={this.onDownloadFile} /> // <-- pass callback as prop
</div>
);
}
}