I'm developing my first app and still learning the flow. So suppose I have a component called:
Parent which holds a method HelloWorld() like the following example:
import React, { Component } from 'react';
class Parent extends Component {
Helloworld() {
console.log('Hello world');
}
render () {
return (
<View>{this.props.children}</View>
)
}
}
module.exports = Parent;
and then i want to import this in to another component and use its method then how do I do it? Ill write another short example of how I would implement it.
import React, { Component } from 'react';
import { Parent } from 'path to parent';
//or
const Parent = require('path to parent');
//which of these is better?
class Home extends Component {
Helloworld() {
console.log('Hello world');
}
render () {
return (
<Parent>
// this is what i need
<Button onClick={parent.Helloword()}>Some Button</Button>
</Parent>
)
}
}
module.exports = Home;
Thank you in advanced for your help.
To call a parent's function from a child component, pass the function reference to the child component as a prop. Then you can call that parent's function from the child component like props. parentMethodName().
To call a parent component method from the child component, we need to pass the changeName() method as a prop to the child component and access it as a props data inside the child component.
In the parent component, create a callback function. This callback function will retrieve the data from the child component. Pass the callback function to the child as a props from the parent component.
While there is no direct way to pass data from the child to the parent component, there are workarounds. The most common one is to pass a handler function from the parent to the child component that accepts an argument which is the data from the child component.
Usually you should pass info from parent to child through props.
parent.jsx:
import Child from './child';
class Parent extends Component {
constructor(props) {
super(props);
this.helloWorld = this.helloWorld.bind(this);
}
helloWorld() {
console.log('Hello world!');
}
render() {
return (
<View><Child method={this.helloWorld} /></View>
);
}
}
child.jsx:
class Child extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Button onClick={this.props.method} />
);
}
}
Edit: about preference between import
and require
, I believe it's a matter of taste, but I think import
is cleaner.
You can read React Native-Tutorial-What's going on here? about import
. and here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With