2017-12-16 9 views
0

機能コンポーネントにpropsとして渡されるonClickHandler関数からreduxアクションを呼び出そうとしていますが、何も起こりません。functionコンポーネントにpropとして渡されたclickHandlerからreduxアクションを呼び出す方法は?

子コンポーネントの小道具としてclickHandlerを渡しています。子コンポーネントとしてParentComponentで処理することは機能コンポーネントです。 parentComponentにため

コード

import React, { Component } from 'react'; 
import { connect,store } from 'react-redux'; 
// import statement for component 
// import statement for redux actions 

class ParentComponent extends Component { 
    constructor(props){ 
    super(props); 
    this.clickHandler = this.clickHandler.bind(this); 
    } 

    clickHandler(data){ 
    // call this.props.actions(data) here; 
    } 

    renderList(){ 
     return <ChildComponent 
      key={field.name} 
      clickHandler={() => this.clickHandler(field.name)} 
      /> 
    }) 
    } 

    render() { 
    return (
     <div className=""> 
     {this.renderList()} 
     </div> 
    ); 
    } 
} 

export default connect(null, { 
    actions 
})(ParentComponent); 

ChildComponentのコード

const ChildComponent = (props) => { 
    return( 
    <span onClick={props.clickHandler} className="glyphicon glyphicon-sort"></span> 
) 
} 
+0

感謝。問題は、別のファイルで同じアクションクリエイターが呼び出されていたことです。アクションクリエイターの名前をユニークなものに変更することで、この問題が解決されました。 – Etherealm

答えて

2

子コンポーネントと子コンポーネントのonClickに小道具を渡す方が良いでしょうが、に引数を渡します関数

親コンポーネントの返信用

import React, { Component } from 'react'; 
import { connect,store } from 'react-redux'; 
// import statement for component 
// import statement for redux actions 

class ParentComponent extends Component { 
    constructor(props){ 
    super(props); 
    this.clickHandler = this.clickHandler.bind(this); 
    } 

    clickHandler(data){ 
    // call this.props.actions(data) here; 
    } 

    renderList(){ 
     return <ChildComponent 
      key={field.name} 
      name={field.name} 
      clickHandler={this.clickHandler} 
      /> 
    }) 
    } 

    render() { 
    return (
     <div className=""> 
     {this.renderList()} 
     </div> 
    ); 
    } 
} 

export default connect(null, { 
    actions 
})(ParentComponent); 

子コンポーネント

const ChildComponent = (props) => { 
    return( 
    <span onClick={()=> props.clickHandler(props.name)} className="glyphicon glyphicon-sort"></span> 
) 
} 
+0

しかし、コンポーネントのレンダリング中にもonClickイベントが発生します。 – Etherealm

+0

私は答えを編集しました。これはそれを行う1つの方法です。別の方法は、props.nameを使って小道具を介して受け取った関数を起動するコンポーネントの中に別の関数を書くことです – Jay

関連する問題