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

时间:2017-05-11 13:44:17

标签: javascript reactjs functional-programming react-router react-jsx

    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 个答案:

答案 0 :(得分:1)

这是一个有效的例子

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>);
}

您还可以在行动here

中看到它

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

答案 1 :(得分:0)

从示例中不完全清楚构造函数中的Card是什么。但是这里有一个如何修改clicked元素的例子。

基本上你只能保持被点击元素的索引处于父状态,然后将它作为一些属性传递给子组件,即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>
   )
 }