Calling a method of a parent component from a child - React Native

I am developing my first application and still learning the flow. Therefore, suppose I have a component:

The parent that contains the HelloWorld () method, as in 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 into another component and use its method, then how to do it? Ill write another short example of how I 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 for your help.

+4
source share
3 answers

Usually you should pass the information from parent to child through the details.

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} />
        );
    }
}

: import require, , , , import .

+2
+1

prop : : this.props.propName() , , , , prop

import React from 'react';
import {
  View,
  Text,
} from 'react-native';

var Parent = React.createClass({   
  render: function() {
    return (
      <Child foo={()=>this.func1()} bar={()=>this.func2()} />
    );
  },
  func1: function(){
    //the func does not return a renderable component
    console.log('Printed from the parent!');
  }
  func2: function(){
    //the func returns a renderable component
    return <Text>I come from parent!</Text>;
  }
});

var Child = React.createClass({   
  render: function() {
    this.props.foo();
    return (
      <Text>Dummy</Text>
      {this.props.bar()}
    );
  },
});

module.exports = Parent;
+1

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


All Articles