Response: calling a method of a child component from the parent component

I have a ScrollView in a native answer and it has many Views. I save the ref for viewing with the following code

cards.push( <Card ref={(ref) => { console.log(ref); this.cardRef[index] = ref; ref.testMethod(); }} /> ); 

A map is a separate component that looks like this:

 class Card extends Component { constructor(props) { super(props); this.testMethod = this.testMethod.bind(this); } testMethod() { console.log('this.is.test.method'); } render() { return ( <View style={styles.container}> <Text>This.is.a.card</Text> </View> ) } } 

However, he says that testMethod is not defined, cannot call ref.testMethod ().

+5
source share
1 answer

I played with your jsfiddle code, and it looks like a child method is being called:

 var Card = React.createClass({ testMethod() { console.log('this.is.test.method'); }, render() { return ( <h1>this is a card.</h1> ) } }); var Parent = React.createClass({ render: function() { return <div><Card ref={(r) => {r.testMethod()}}/></div>; } }); ReactDOM.render( <Parent />, document.getElementById('container') ); 

https://jsfiddle.net/vq110d69/

+3
source

Source: https://habr.com/ru/post/1238012/


All Articles