2016-07-29 171 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