繁体   English   中英

在本机反应中更改可按颜色时遇到问题。 我让它在没有数组的情况下工作,我是否遗漏了一些明显的东西?

[英]Having trouble changing pressable color in react native. I had it working without it being an array, am I missing something obvious?

我的目标是单击按钮并让按钮更改颜色,直到我再次单击它。 我的代码使用单个按钮,但是当我尝试制作一系列按钮时遇到了麻烦,我觉得我错过了一些明显但找不到的东西

//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};
`;

这是任何想查看它的人的更新代码

//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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM