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

我每次點擊的卡我所有元素的改變狀態之一,我該怎麼辦編程這隻改變我點擊的卡片?React.JS - 多個元素共享的狀態(?如何修改只有一個元素,而不會影響其他人)

回答

0

這裏的工作示例

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

顯然這是一個人爲的例子,基於你的代碼,在現實世界中ap你不會像{1: true, 2: false}那樣存儲硬編碼狀態,但它顯示了概念

0

從示例中不完全清楚構造函數中的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> 
    ) 
} 
相關問題