I have 2 components A
and B
as below,
class A extends Component {
testMethodA() {
}
render() {
return (
<View style={[styles.scene, {backgroundColor: 'red'}]}>
<TouchableHighlight onPress={this.onPress}>
<Text>Welcome. Press here!</Text>
</TouchableHighlight>
</View>
);
}
}
class B extends Component {
testMethodB() {
}
render() {
return (
<View style={[styles.scene, {backgroundColor: 'red'}]}>
<TouchableHighlight onPress={this.onPress}>
<Text>Welcome. Press here!</Text>
</TouchableHighlight>
</View>
);
}
}
How can I access testMethodA
from B
and testMethodB
from A
?
The simplest form of communication between components is via properties — usually called props. Props are the parameters passed into child components by parents, similar to arguments to a function.
js do <Button onPress={movePopUpCard}></Button> . With calling the function directly, the return value of the function will be passed to onPress .
There are two ways to get access to another component methods:
child accesses a parent method - props
class Child extends Component {
render() {
return (<div>{this.props.formatMessage(10)}</div>)
}
}
class Parent extends Component {
formatMessage(number) {
return '$' + number;
}
render() {
return (<Child formatMessage={this.formatMessage} />);
}
}
parent accesses a child method - refs
class Child extends Component {
getInnerData() {
return 'some inner data';
}
render() {
return (<div>child component</div>)
}
}
class Parent extends Component {
componentDidMount() {
const childData = this.refs.child.getInnerData();
}
render() {
return (<Child ref='child' />);
}
}
What you should do is have a common parent that will hold the data of componentA & componentB and pass it between them as needed.
class Child1 extends Component {
componentDidMount() {
this.props.onMount('child 1');
}
render() {
return (<div>I'm child1. child2 data is: {this.props.data}</div>)
}
}
class Child2 extends Component {
componentDidMount() {
this.props.onMount('child 2');
}
render() {
return (<div>I'm child2. child1 data is: {this.props.data}</div>)
}
}
class Parent extends Component {
render() {
return (
<div>
<Child1 onMount={(msg => this.setState(child1: msg)} data={this.state.child2} />
<Child2 onMount={(msg => this.setState(child2: msg)} data={this.state.child1} />
</div>
);
}
}
You can also combine the first & second methods (props & refs) to get the methods of componentA & componentB and pass them as props to you componentB & componentA respectively, but this is really not recommended
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