2016-07-29 96 views
4

我正在開發我的第一個應用程序並仍在學習流程。 因此,假設我有一個名爲組件:調用子組件的方法 - React Native

母公司持有的方法的HelloWorld(),如下面的例子:

import React, { Component } from 'react'; 

class Parent extends Component { 
    Helloworld() { 
     console.log('Hello world'); 
    } 

    render() { 
     return (
      <View>{this.props.children}</View> 
     ) 
    } 
} 

module.exports = Parent; 

,然後我想在另一個組件導入此並使用它的方法,那麼如何我要做嗎?我寫了另一個我將如何實現它的簡短例子。

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; 

謝謝你的幫助。

回答

2

通常你應該通過道具父母傳遞信息給孩子。

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:

​​

編輯:約importrequire之間的喜好,我相信這是一個品味的問題,但我認爲import更乾淨。

+0

謝謝你回到我身邊。我沒有時間來測試,但我會盡快給你反饋。 – TheMan68

+0

關於導入還有另一個區別,並且我忘了提及:'import'只能用於文件的開頭,而'require'可以在任何地方使用。 – lalkmim

+0

這兩個答案在這裏工作,但我覺得這是一個更適合我需要的一點。非常感謝你 – TheMan68

1

我們可以通過一個道具在子類: 然後從孩子叫它:this.props.propName() 我們可以通過字符串,數字,職能,陣列,在對象支撐

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; 
+0

謝謝你回到我身邊。我沒有時間來測試,但我會盡快給你反饋。 – TheMan68

+0

這個答案也很好,只是上面的答案更適合我需要的東西。謝謝 – TheMan68