React.JS - 共享状态的多个元素(如何仅修改其中一个元素而不影响其他元素?) [英] React.JS - multiple elements sharing a state ( How do I modify only one of the elements without affecting the others? )
本文介绍了React.JS - 共享状态的多个元素(如何仅修改其中一个元素而不影响其他元素?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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>
)
}
每次我点击其中一张卡片时,我的所有元素都会改变状态,如何编程才能更改我点击的卡片?
Every time I click on one of the cards all of my elements change states, how do I program this to only change card that I clicked?
推荐答案
这是一个工作示例
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>);
}
您还可以看到它的实际效果 这里
You can also see it in action here
显然这是一个人为的例如,根据您的代码,在实际应用程序中,您不会存储硬编码状态,如 {1:true,2:false}
,但它显示了概念
Obviously this is a contrived example, based on your code, in real world application you wouldn't store hardcoded state like {1: true, 2: false}
, but it shows the concept
这篇关于React.JS - 共享状态的多个元素(如何仅修改其中一个元素而不影响其他元素?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文