簡體   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