React.JS - 多个元素共享一个状态(如何只修改一个元素而不影响其他元素?)

IT技术 javascript reactjs functional-programming react-router react-jsx
2021-05-07 11:21:34
    class App extends Component {
       constructor(props) {
       super(props);
       this.state = { Card: Card }
      }
      HandleEvent = (props) => {
        this.SetState({Card: Card.Active}
         }
      render() {
       return (
         <Card Card = { this.state.Card } HandleEvent={ 
       this.handleEvent }/>
         <Card Card = { this.state.Card } HandleEvent={
       this.handleEvent }/>
       )
      }
    }
     const Card = props => {
        return (
        <div style={props.state.Card} onClick={ 
            props.HandleEvent}>Example</div>
         )
       }

每次我点击其中一张卡片时,我的所有元素都会改变状态,我该如何编程以仅更改我点击的卡片?

2个回答

这是一个工作示例

import React, { Component } from 'react'
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      0: false,
      1: false
    };
  }

  handleEvent(idx) {
    const val = !this.state[idx];
    this.setState({[idx]: val});
  }

  render() {
    return (
      <div>
        <Card state={this.state[0]} handleEvent={()=>this.handleEvent(0) } />
        <Card state={this.state[1]} handleEvent={()=>this.handleEvent(1) } />
      </div>
    ); 
  }
}

const Card = (props) => {
  return (<div onClick={() => props.handleEvent()}>state: {props.state.toString()}</div>);
}

你也可以在这里看到它的实际效果

显然,这是一个人为的例子,根据您的代码,在现实世界的应用程序中,您不会像 那样存储硬编码状态{1: true, 2: false},但它显示了这个概念

从示例中并不完全清楚构造函数中的 Card 是什么。但这里是如何修改单击元素的示例。

基本上,您只能在父状态中保留单击元素的索引,然后将其作为某些属性传递给子组件,即isActive这里:

const cards = [...arrayOfCards];

class App extends Component {
   constructor(props) {

   super(props);
   this.state = { activeCardIndex: undefined }
  }
  HandleEvent = (index) => {
    this.SetState({
      activeCardIndex: index
    });
  }
  render() {
   return ({
      // cards must be iterable
      cards.map((card, index) => {
        return (
          <Card
            key={index}
            Card={Card}
            isActive={i === this.state.activeCardIndex}
            HandleEvent={this.HandleEvent.bind(this, index)}
          />
        ); 
      })
   });
  }
}

const Card = props => {
  // style active card
  const style = Object.assign({}, props.Card, {
    backgroundColor: props.isActive ? 'orange' : 'white',
  });

  return (
  <div style={style} onClick={ 
      props.HandleEvent}>Example</div>
   )
 }