2016-05-11 11 views
7

この質問の例をいくつか見てきましたが、いずれもうまく動作しないか、またはすべての方法が完全に理解できるかを完全に理解できませんでした。私はParentListViewと呼ばれるコンポーネントを持っていて、もう1つはChildCell(リストビュー内の行)です。のChildCellからParentListViewの関数を呼びたいと思っています。React-Native ListView行の子コンポーネントから親関数を呼び出す

class ChildCell extends Component { 

    pressHandler() { 
    this.props.onDonePress; 
    } 

    render() { 
    return (
     <TouchableHighlight onPress={() => this.pressHandler()} > 
      <Text>Child Cell Button</Text> 
     </TouchableHighlight> 
    ); 
    } 

} 

ParentListViewで:

class ParentListView extends Component { 

//... 

    render() { 

    return (
     <ListView 
     dataSource={this.state.dataSource} 
     style={styles.listView} 
     renderRow={this.renderCell} 
     renderSectionHeader={this.renderSectionHeader} 
     /> 
    ); 
    } 

    renderCell() { 
    return (
     <ChildCell onDonePress={() => this.onDonePressList()} /> 
    ) 
    } 

    onDonePressList() { 
    console.log('Done pressed in list view') 
    } 

} 

私はそれがすべての適切なコードだと思います。私はChildCellを願って登録するように報道陣を得ることができますが、その方法はParentListViewに出ることができません。私は何が欠けていますか?

ありがとうございます!

UPDATE 1:ParentListView

私はこれに渡された小道具を変更する場合:セルをレンダリングするとき

<ChildCell onDonePress={this.onDonePressList.bind(this)} /> 

私はコンパイル時にUnhandled JS Exception: null is not an object (evaluating 'this.onDonePressList')エラーが発生します。

私はこのように直接にconsole.logを置く場合:それはメッセージの罰金をログに記録します

<ChildCell onDonePress={() => console.log('Done pressed in list view')} /> 

。私はもともと持っていたように私はそれを残す場合は

それは Unhandled JS Exception: null is not an object (evaluating '_this2.onDonePressList')

UPDATEとにButtonPressにクラッシュ

<ChildCell onDonePress={() => this.onDonePressList()} /> 

2:

OK、私は、コンストラクタのような方法を結合しようとしていますso:

class ParentListView extends Component { 
    constructor(props) { 
    super(props); 
    this.onDonePressList = this.onDonePressList.bind(this); 
    this.state = {...}; 
} 

しかし、 ror:null is not an object (evaluating 'this.onDonePressList')と実行されません。

UPDATE 3: Here is a link to a react native playground

+0

コンストラクタ関数でコンポーネントを書き込もうとしましたか? 「すべてのインスタンスに対して一度だけバインドされるように、コンストラクタでイベントハンドラをバインドすることをお勧めします。」https://facebook.github.io/react/docs/reusable-componentshtml – Maxwelll

+0

私は試しましたが(アップデート2参照)、無駄です。 '()=> myFunction()'は私のバインディングを行いませんか? '未処理のJSの例外を::nullはオブジェクトではありません(評価「_this2.onDonePressList」)' –

答えて

6

このようpressHandleronDonePressを呼び出してみてください。

pressHandler() { 
    this.props.onDonePress() 
} 

また、あなたのrenderRowrenderSectionHeaderthisをバインド:

<ListView 
    dataSource={this.state.dataSource} 
    style={styles.listView} 
    renderRow={this.renderCell.bind(this)} 
    renderSectionHeader={this.renderSectionHeader.bind(this)} 
    /> 

私が設定しましたabovを使用した例here e関数。

https://rnplay.org/apps/DcdAuw

+0

あなたはうまく働きます。私は 'はconsole.log(「リストビューに押さ完了」)} />'を試してみましたが、それは動作しますが、親は 'this'を使用して、独自の機能を呼び出すために取得しようとしているようです問題がある... –

+0

うーん、わからない理由、それはここで働いています:https://rnplay.org/apps/kDxeug –

+0

私が得ることのように呼び出す –

関連する問題