如何从另一个组件激活功能

时间:2020-09-04 06:19:17

标签: javascript reactjs

当单击一个元素时,我试图从另一个组件中调用一个函数。我从文件导入了该函数,但是它不起作用。我可以通过这种方式从另一个组件调用该函数,还是需要使用其他方法?

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>
    );
  }
}

1 个答案:

答案 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>
    );
  }
}