简体   繁体   中英

React call a function from another class ES6

 class F1 extends React.Component{ hot(){ alert("Hot function running"); } lot(){ let t = this; ReactDOM.render(<F2 yF={() => { t.hot(); }} />,document.getElementById("b")); } render(){ return ( <button onClick={this.lot}>F1 click</button> ); } } class F2 extends React.Component{ constructor(props){ super(props); } render(){ return ( <button onClick={this.props.yF}>F2 click</button> ); } } ReactDOM.render(<F1 />,document.getElementById("a"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="a"></div> <div id="b"></div> </body> </html>

https://jsbin.com/poqofohiqa/edit?html,js,console,output

I want to call a function that is inside class F1 when i click Button F2 the function inside F1 should be executed.

Currently im trying to pass the function from F1 to F2 but its not working

UPDATE 1

To make it simple ...

Im trying to call hot function inside F1 by clicking the button on F2

You need to bind lot method to this in constructor method. Then only it will get the context

 class F1 extends React.Component{ constructor() { super(); this.lot = this.lot.bind(this); } hot(){ alert("Hot function running"); } lot(){ ReactDOM.render(<F2 yF={() => { this.hot(); }} />,document.getElementById("b")); } render(){ return ( <button onClick={this.lot}>F1 click</button> ); } } class F2 extends React.Component{ constructor(props){ super(props); } render(){ return ( <button onClick={this.props.yF}>F2 click</button> ); } } ReactDOM.render(<F1 />,document.getElementById("a"));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div id="a"></div> <div id="b"></div> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM