首页 > 解决方案 > 如何从一个组件调用函数到另一个组件?反应

问题描述

我在 react.js 工作。我创建了一个组件Backend.jsx。我希望它作为一种服务(如角度)工作,我可以在其中发送 API 请求。我想调用Backend其他一些组件中的方法。

我在组件中调用了这个后端服务,并尝试发送数据并BackendService使用道具获取它。

但显然这行不通。

这是我的代码

组件中:

这将在表单提交后调用。

handleLoginSubmit = (event) => {
    event.preventDefault();
    console.log(this.state.data);
    <BackendService onSendData = {this.state.data} />
}

后端服务中

constructor(props) {
    super(props);
    this.state = {  }
    this.login(props)
}
login = (props) =>
{
    console.log('login', props);
};

任何建议我如何logincomponent. 或任何其他获得服务组件数据的建议。

标签: javascriptreactjsinstancefunction-call

解决方案


你可以试试这个:

1.Component.js

class Componet extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      data:"this state contain data"
    }

    this.backendServiceRef = React.createRef(); // Using this ref you can access method and state of backendService component.
  }

  render() {
    return (
      <div className="App">
        <button onClick={() => {

          this.backendServiceRef.current.login()  

       }}>click</button>

        <BackendService ref={this.backendServiceRef} onSendData = {this.state.data}></BackendService>
      </div>
    );
  }
}

export default Componet;  

2.后端服务.js

class BackendService extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    }
  }

  login = (props) => {
    alert("login call")
  };

  render() {
    return (
      <div>
        Backend service component
      </div>
    )
  }
}

推荐阅读