reactjs - 您如何为组件的每个实例赋予其独立变化的道具?
问题描述
它当前的设置方式是,当单击一个cell
组件时,每个单元格的背景颜色都会变为红色或黑色,而不仅仅是那个单元格。我怎样才能使每个cell
组件的currentColor
道具都是独一无二的并且独立更改?
相关位来自App.js
:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
grid: [
[{},{},{},{},{},{},{}],
[{},{},{},{},{},{},{}],
[{},{},{},{},{},{},{}],
[{},{},{},{},{},{},{}],
[{},{},{},{},{},{},{}],
],
currentColor: "red",
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('The circle was clicked and will change to this color: ' + this.state.currentColor);
if (this.state.currentColor === "red"){
this.setState(state => ({
currentColor: "black"
}));
}
else{
this.setState(state => ({
currentColor: "red"
}));
}
}
render(){
console.log("Grid length is: " + this.state.grid.length)
return (
<div className="App">
<GridContainer grid={this.state.grid} currentColor={this.state.currentColor} handleClick={this.handleClick}/>
</div>
);
}
}
export default App;
然后以这种方式传递这些道具:App -> GridContainer -> RowContainer -> Cell
子组件Cell.js
:
import React, { Component } from 'react';
import styled from 'styled-components'
const StyledCell = styled.div`
background-color: ${props => props.currentColor};
border-radius: 50%;
margin: 1rem;
width: 133px;
height: 100px;
`;
class Cell extends Component {
render() {
return(
<StyledCell onClick={this.props.handleClick} currentColor = {this.props.currentColor}>
</StyledCell>
)
}
}
export default Cell;
解决方案
由于您在顶层更改了一次颜色,因此将相同的值传递给所有子组件。如果您想拥有特定于每个组件实例的颜色,您可以为 Cell 组件提供内部状态以控制其自己的颜色,或者将每个单元格的颜色独立存储在网格对象中,然后映射数组并传递每个颜色作为道具并调整处理程序以提升单元格的状态更改。我会举一个例子,但它几乎是 5。干杯。
更新:
我认为第二种方法可能更好,在这种情况下,您可以将应用程序的网格状态转换为:
this.state.grid = [
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }],
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }],
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }],
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }],
[{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" },{ color: "red" }]
]
并将您的点击处理程序替换为为您定位的特定单元格设置颜色的处理程序:
function colorCell(row, col, color) {
let grid = Array.from(this.state.grid);
grid[row][col].color = color;
this.setState({ grid: grid })
}
像您正在做的那样,将该函数作为道具一直传递给您的单元格,以及它们各自的行/列索引,并在附加到单元格的单击处理程序中调用它。
无论如何,这就是要点。
推荐阅读
- hyperledger-fabric - 在 hyperledger 结构中使用非管理员卡和 composer-rest-server
- python - 设置对象在套接字模块中没有属性“编码”
- r - 在R中的数据框中旋转行和列
- mysql - 更新语句中的 MySQL 语法错误,NodeJS(MySQL2) 模块
- python - Python:如何在我的文件结果之后再打印一行?
- java - Firestore whereEqualTo、orderBy 和 limit(1) 不起作用
- html - 这个文本区域周围的额外空间来自哪里?
- git - 在 git 克隆一个 repo 之后,我只得到一个分支而不是所有分支。Android Studio 无法识别其余部分
- c# - 如何递归地编写插值搜索?- C#
- ios - 自动布局后从 Xib 加载视图获取调整框架子视图的大小