how to get callback from child to parent class in

2019-07-27 03:50发布

问题:

I have to render few tabs. ONclick of it, it should get highlighted. I have tabList object coming from reducer (hard-coded value). onclicking of a tab a action is generated which set the "state" with clicked tab object(I call it "activeTab").

while rendering the tabList (all the tabs) I am checking if "rendered_tabid == active_tabid" then add a class "active" (it is conditional basis)

active-tab-reducer.js

export const tabReducer = () => {
    return [
      {
        id: 1,
        name:"Dental Page",
        url: '#dentalPage'
      },
      {
        id: 2,
        name:"Vision Page",
        url: '#visionPage'
      },
      {
        id: 3,
        name:"Other page Tab",
        url: '#OtherPage'
      }
    ]
}


const activeTabReducer = (state = {}, action) => {
  switch(action.type) {
    case "TAB_SELECTED": return action.payload;
      break;
  }
  return state;
}

export default activeTabReducer;

(combined-reducer) index.js

import {combineReducers} from 'redux';
import activeTabReducer, {tabReducer} from './active-tab-reducer';

const allReducers = combineReducers({
  tabList: tabReducer,
  activeTab: activeTabReducer
});

export default allReducers;

(action) index.js

export const selectTab = (tab) => {
  console.log('action invoked', tab);
  return {
    type: "TAB_SELECTED",
    payload: tab
  }
} 

tablist.js

import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {selectTab} from '../actions/index';
import TabsListItem from './tabsListItem';

class TabList extends React.Component {
  constructor(props){
    super(props);
  }

  createTabItems(){    
    return this.props.tabList.map((item, i) => {
      return (
        <TabsListItem key={i} tabList={item} /> 
      )
    });
  }

  render() {

    return (
      <div id="layout-header" className="layout-header">
        <div id="header" className="header">
          <ul className="tabs tabs--horizontal">                  
            {this.createTabItems()}    
          </ul>
        </div>
      </div>
    );
  }
};

function mapStateToProps(state) { 
  return {
    tabList: state.tabList,
    activeTab: state.activeTab      
  }
}
function matchDispatchToProps(dispatch){
  return bindActionCreators({selectTab: selectTab}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(TabList);

tabListItem.js

import React from 'react';
class  TabListItem extends React.Component {
  constructor(props){
    super(props);
    console.log(this.props.tabList)
  }

  render() {   
    return (
      <li onClick={() => this.props.selectTab(this.props.tabList)}
          className={"tab  "+((this.props.activeTab.id==item.id)?'active':'')+""+( (this.props.activeTab.id==undefined) && (item.id == 1)?'active':'' ) 
          role="presentation" className={"tab  " }>
          <a href="#"> 
            <div className="tab__label">   
              <div className="tab__label__value">{this.props.tabList.name}</div>
            </div>
          </a>
      </li>        
    );
  }
};
export default TabListItem;

when I click any tab (from tabListItem), a action TAB_SELECTED action should dispatch, which set the state with "activeTab" object.

How to generate action from child?

回答1:

You should pass a function to the child component via props.

As the action has a parameter to select the correct tab, you can use a function returning a function:

createTabItems() {    
 return this.props.tabList.map((item, i) => {
   return (
     <TabsListItem key={i} tabList={item} onSelect={() => this.onSelect(i).bind(this)} /> 
   );
});

}

In this way your child component calls your method onSelect passing the correct parameter.

In your onSelect method on the parent (container) component you will then dispatch your action:

onSelect(i) {
  this.props.selectTab(i);
}