如何重新渲染我点击的内容 - 做出反应
How re-render just copmonent to which I clicked - react
我正在尝试在 React 中制作一个简单的颜色记忆游戏(找到两个相同图像的位置)。
当我点击一张卡片时,所有其他卡片都会重新呈现。我该如何防止这种情况?
//app class
handleClick = index => {
this.setState((prevState) => {
var temp = [...prevState.clickedPicture, index]
return{clickedPicture: temp}
})
}
isClicked = (index) => this.state.clickedPicture.indexOf(index) === -1
render() {
return(
<div className="content">
<div className="header">
<h1>Memory</h1>
</div>
<div className="main">
_.shuffle(this.state.colors).map((current,index) =>
<Game
key={index}
index={index}
current={current}
status={this.state.status}
handleClick={this.handleClick}
bool={this.isClicked(index)}
/>)
</div>
}
// Game component
class Game extends Component {
clickHandle = () => {
if(this.props.bool){
this.props.handleClick(this.props.index)
}
}
render() {
return(
<div className={this.props.status}
style={{ backgroundColor: this.props.bool ?
'black' : this.props.current }}
onClick={this.clickHandle}>
</div>
);
}
}
让 Cards 成为自己的组件,以便它们可以访问生命周期挂钩。然后
使卡片成为 PureComponents,因此它们只会在对道具的引用发生变化时更新。
我正在尝试在 React 中制作一个简单的颜色记忆游戏(找到两个相同图像的位置)。
当我点击一张卡片时,所有其他卡片都会重新呈现。我该如何防止这种情况?
//app class
handleClick = index => {
this.setState((prevState) => {
var temp = [...prevState.clickedPicture, index]
return{clickedPicture: temp}
})
}
isClicked = (index) => this.state.clickedPicture.indexOf(index) === -1
render() {
return(
<div className="content">
<div className="header">
<h1>Memory</h1>
</div>
<div className="main">
_.shuffle(this.state.colors).map((current,index) =>
<Game
key={index}
index={index}
current={current}
status={this.state.status}
handleClick={this.handleClick}
bool={this.isClicked(index)}
/>)
</div>
}
// Game component
class Game extends Component {
clickHandle = () => {
if(this.props.bool){
this.props.handleClick(this.props.index)
}
}
render() {
return(
<div className={this.props.status}
style={{ backgroundColor: this.props.bool ?
'black' : this.props.current }}
onClick={this.clickHandle}>
</div>
);
}
}
让 Cards 成为自己的组件,以便它们可以访问生命周期挂钩。然后 使卡片成为 PureComponents,因此它们只会在对道具的引用发生变化时更新。