簡體   English   中英

React js:訪問其他組件的狀態

[英]React js: Accessing state of other components

我有一個使用以下代碼構建的組件。 目的是在卡上添加一個類,以在單擊卡中的按鈕時突出顯示該類。 但是,以下代碼在首次點擊時有效,但在隨后的點擊中無效。 我知道刪除類時必須將其他元素的單擊狀態設置為false。 如何才能做到這一點?

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;

將邏輯包含在父組件中會更容易嗎? 因為它“知道”所有子卡組件。

有類似...

this.state = { selectedComponent: null };

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

...在渲染中:

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

這行得通嗎?

最好的方法將是解除狀態。 像這樣:

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;

盡管使用一些數據id比索引值更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM