Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react: Calling child component's method from parent component

I have a ScrollView in react native and it has many Views. I store the ref to view using the following code

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

Card is a separate component which 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 it says that testMethod is undefinded, cannot call ref.testMethod().

like image 889
meteors Avatar asked Oct 18 '22 20:10

meteors


1 Answers

I played with your code on jsfiddle, and it looks like the child method is 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/

like image 134
alek kowalczyk Avatar answered Oct 22 '22 03:10

alek kowalczyk