简体   繁体   中英

React js: Accessing state of other components

I have a component built using the below code. The aim is to add a class on the card to highlight it when the button inside it is clicked. However, the below code works on the first click but doesn't work for the subsequent clicks. I understood that I have to set the clicked state of other elements to false when I remove the class. How can this be done?

import React, { Component } from 'react';
import './PricingCard.css';

class PricingCard extends Component {

  constructor(){
    super();
    this.state = {
      clicked : false
    }
  }

  makeSelection(){

    let elems = document.getElementsByClassName('Card');
    for(var i=0;i<elems.length;i++){
      elems[i].classList.remove("active");
    }
    this.setState({clicked: true});

  }




  render() {

    var activeClass = this.state.clicked ? 'active' : '';

    return (
      <div className= {"categoryItem Card " + this.props.planName + " " +activeClass}>
        <div className="cardDetails">
          <div> {this.props.planName} </div>
          <div className="pricing"> {this.props.price} </div>
          <button onClick={this.makeSelection.bind(this)} className="buttonPrimary"> Select this plan </button>
          <div className="subtitle"> {this.props.footerText} </div>
        </div>
      </div>
    );
  }
}

export default PricingCard;

Wouldn't it be easier to have the logic in a parent component? Since it is "aware" of all the child Card components.

Have something like...

this.state = { selectedComponent: null };

onClick(card_id) {
   this.setState({ selectedComponent: card_id });
}

...in render:

const cards = smth.map((card) => 
    <Card onClick={this.onClick.bind(this, card.id)} 
        isActive={map.id === this.state.selectedComponent} />

Would this work?

Best way will be to lift lift the state up. Like this:

class PricingCardContainer extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      selectedCard: NaN,
    }
  }

  handleCardClick(selectedCard){ this.setState({ selectedCard }); }

  render() {
    return (
      <div>{
        this.props.dataArray.map((data, i) => 
          <PricingCard
            key={i} 
            className={this.state.selectedCard === i ? 'active': ''}
            price={data.price}
            onClick={() => this.handleCardClick(i)}
            footerText={data.footerText}
            planName={data.planName}
            plan={data.plan}
          />
        )
      }</div>
    )
  }
}


const PricingCard = ({ className = '', planName, price, onClick, footerText }) => (
  <div className= {`categoryItem Card ${planName} ${className}`}>
    <div className="cardDetails">
      <div> {planName} </div>
      <div className="pricing"> {price} </div>
      <button onClick={onClick} className="buttonPrimary"> Select this plan </button>
      <div className="subtitle"> {footerText} </div>
    </div>
  </div>
);

export default PricingCard;

Although it would be better to use some data id than index value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM