2016-07-29 12 views
4

私は最初のアプリケーションを開発していて、まだフローを学習しています。次の例のような方法の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

関連する問題