Skip to content

Instantly share code, notes, and snippets.

@Spazcool
Last active April 12, 2018 13:06
Show Gist options
  • Save Spazcool/fff2cf78b715d830e95d0fb2b8169512 to your computer and use it in GitHub Desktop.
Save Spazcool/fff2cf78b715d830e95d0fb2b8169512 to your computer and use it in GitHub Desktop.
two-level method pass in React
import Child from './Child';
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state={
trueOrfalse: true,
};
this.method = this.method.bind(this);
}
method(e){
this.setState({
trueOrfalse: true ? false : true,
});
console.log("true or false: ", this.state.trueOrfalse);
console.log("data: ", e);
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<Child passedMethod={this.method} data={"trash data"}/>
</div>
);
}
}
export default App;
import Grandchild from './Grandchild';
import React, { Component } from 'react';
import './App.css';
class Child extends Component {
render() {
return (
<div>
<p>Text from inside child</p>
<Grandchild passedMethod={this.props.passedMethod} passedData={this.props.data}/>
</div>
);
}
}
export default Child;
import React, { Component } from 'react';
import './App.css';
class Grandchild extends Component {
render() {
return (
<div>
<p onClick={() => this.props.passedMethod(this.props.passedData)}>Text from inside Grandchild</p>
</div>
);
}
}
export default Grandchild;
@Spazcool
Copy link
Author

This test app works, passing the parent method through the child component and to the grandchild.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment