Change the items in the list in React when the item was clicked.

I'm new to ReactJS, and it's hard for me to understand how different components can communicate with each other.

I have a component that will display a list, and each list item is a different component. I want the components to be as small as possible.

Now each list item can have a property with a name active, and if the property is set to true, an additional class is added.

This is a class that defines a single element in a component.

See this code below for my component defining a single list item:

export default class OfficeRibbonTab extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      active: props.active ? props.active : false
    }

    // Assign all the correct event handlers.
    this.setActive = this.setActive.bind(this);
  }


  setActive() {
    this.setState({active: true});
  }

  render() {
    // When the tab is defined as active, add the "active" class on it.
    if (this.state.active)
    { var tabClassName = "active"; }

    return <li onClick={this.setActive} className={tabClassName}>{this.props.tabName}</li>;
  }
}

, active, , . , , . , , , active false.

:

export default class OfficeRibbon extends React.Component {

  constructor(props) {
    // Call the 'base' constructor.
    super(props);
  }

  render() {
    var tabs = [];

    // Loop over all the tab elements and define how the element should be rendered.
    for (var i = 0; i < this.props.dataSource.tabs.length; i ++)
    {
      if (i == 1)
      { tabs.push(<OfficeRibbonTab active={true} key={this.props.dataSource.tabs[i].name} tabName={this.props.dataSource.tabs[i].name}></OfficeRibbonTab>); }
      else
      { tabs.push(<OfficeRibbonTab key={this.props.dataSource.tabs[i].name} tabName={this.props.dataSource.tabs[i].name}></OfficeRibbonTab>); }
    }

    return (<div>
      <div className="wrap-top">
        <OfficeRibbonTitle title={this.props.title}/>

        <ul className="tabs">
          {tabs}
        </ul>

      </div>

    </div>);
  }
}

, , .

, ?

+4
1

, OfficeRibbonTab , , . , :

, OfficeRibbon handleTabSelect, OfficeRibbonTab. OfficeRibbonTab, , :

OfficeRibbonTab.jsx

 setActive(tabIndex) {
    this.props.handleTabSelect(tabIndex);
 }

OfficeRibbon.jsx

 handleTabSelect(tabIndex) {
    this.setState({activeIndex: tabIndex});
 }

OfficeRibbon , activeIndex activeId, . OfficeRibbon, a render() . activeIndex , render():

<OfficeRibbonTab active={index === this.state.activeIndex} onClick={this.handleTabSelect} ... />
+3

All Articles