[英]Having trouble changing pressable color in react native. I had it working without it being an array, am I missing something obvious?
The goal I have is to click on the button and for the button to change color until I click it again.我的目标是单击按钮并让按钮更改颜色,直到我再次单击它。 I had the code working with a single button but when I tried to make an array of buttons I ran into trouble, I feel like I misses something obvious but can't find it
我的代码使用单个按钮,但是当我尝试制作一系列按钮时遇到了麻烦,我觉得我错过了一些明显但找不到的东西
//GRID.js
import React, { useState, useEffect } from "react";
import { Cell } from "./cell";
export const Grid = () => {
const ARRAYLENGTH = 3;
const [grid, setGrid] = useState(Array(ARRAYLENGTH).fill({ show: true }));
useEffect(() => {
console.log("updated");
}, [grid]);
const handlePress = (index) => {
let tempGrid = grid;
tempGrid[index].show = !tempGrid[index].show;
setGrid(tempGrid);
console.log(grid[index].show);
logGrid();
};
const logGrid = () => {
console.log(grid);
};
//Renders cell.js
return grid.map((item, index) => {
return (
<Cell
key={`${item} ${index}`}
show={grid[index].show}
index={index}
onClick={handlePress}
/>
);
});
};
//CELL.JS
import React, { useState, useEffect } from "react";
import styled from "styled-components/native";
import { View, Pressable } from "react-native";
import * as theme from "../../config/theme";
//Styles
const StyledCell = styled(Pressable)`
padding: 30px;
border-color: black;
border-width: 1px;
background-color: ${(props) => props.color};
`;
Here is the updated code for anyone who would like to see it这是任何想查看它的人的更新代码
//grid.js
import React, { useState } from "react";
import { Cell } from "./cell";
export const Grid = () => {
const ARRAYLENGTH = 4;
const [grid, setGrid] = useState(
Array(ARRAYLENGTH)
.fill()
.map(() => ({ show: true }))
);
const handlePress = (index) => {
let tempGrid = [...grid];
tempGrid[index].show = !tempGrid[index].show;
setGrid(tempGrid);
};
return grid.map((item, index) => {
return (
<Cell
key={`${item} ${index}`}
show={item.show}
index={index}
onClick={handlePress}
/>
);
});
};
//cell.js //cell.js
import React, { useState, useEffect } from "react";
import styled from "styled-components/native";
import { View, Pressable } from "react-native";
import * as theme from "../../config/theme";
const StyledCell = styled(Pressable)`
padding: 30px;
border-color: black;
border-width: 1px;
background-color: ${(props) => props.color};
`;
export const Cell = ({ show, onClick, index }) => {
const [color, setColor] = useState(theme.blue);
useEffect(() => {
if (show === true) {
setColor(theme.blue);
} else {
setColor(theme.white);
}
}, [show]);
return (
<View>
<StyledCell
color={color}
onPress={() => {
onClick(index);
}}
/>
</View>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.