当我更改(布尔)状态属性值时,为什么我的 React 功能组件无法重新呈现?

问题描述 投票:0回答:1

我有一个简单的 React 组件,它呈现一个 div,它是一个包含 2 行和 2 列的网格容器。它还呈现一个按钮。

我有一个 JSX 数组,用于放置在网格中的四个红色背景 div。

我有另一个 JSX 数组,用于四个黄色背景的 div,当我单击一个按钮时,我想进入网格而不是红色的。

为了强制重新渲染,我正在更改按钮的 onClick 处理程序中状态属性的值。

问题是,当我单击按钮时,网格中的方块不会从红色变为黄色。红色的留在那里。

这是我的代码:

import { useState, useRef } from "react";
import React from 'react';
import './styles.css';


export default function MyComponent() {

// state property that code will change 
// to force a rerender:
const [rerender, setRerender] = useState(false)

// ref that code reads to conditionally
// render the squares in the grid div: 
const whatToShowInGrid = useRef(0)


let myArray = [1,2,3,4]

// The red squares get put into array displaySquares:
let displaySquares  = myArray.map(member=> <div className="divRedBackground" key={member} ></div>)
 
// The yellow squares get put into array displaySquares1:
let displaySquares1 = myArray.map(member=> <div className="divYellowBackground" key={member} ></div>)


// click handler for the button:
function changeSquaresInGrid(){
console.log(`You clicked the button!`)

// Simply toggle the value of whatToShowInGrid.current
// from 0 to 1:
    if (whatToShowInGrid.current === 0) {
        whatToShowInGrid.current = 1
                                        }

    if (whatToShowInGrid.current === 1) {
        whatToShowInGrid.current = 0
                                        }

// force a rerender by toggling the value of 
// state property rerender from false to true:
setRerender(!rerender)
                           }


    return (
      <>
      {/*The grid container*/}
      <div className='gridContainer'>
      { whatToShowInGrid.current === 0 ? <>{displaySquares}</> : <>{displaySquares1}</> }   
      </div>


      {/*The button*/}
      <div className="button1" onClick={changeSquaresInGrid}>
        <p className="button1Text">Click me</p>
      </div>
      </>
           );

                                 }

javascript reactjs react-hooks
1个回答
1
投票

为什么不设置 one 而不是有两组 div,然后在单击按钮时更改它们的背景颜色。

const { useState } = React;

function Example() {

  // Initialise state to red
  const [ background, setBackground ] = useState('red');

  // Create a set of boxes
  function createGrid() {
    return [1, 2, 3, 4].map(el => {
      const id = el + 1;
      const cn = ['box', background].join(' ');
      return <div key={id} data-id={id} className={cn}></div>;
    });
  }

  // Function to toggle between red and yellow
  // and set the new state
  function switchBackground() {
    setBackground(prev => prev === 'red' ? 'yellow' : 'red');
  }

  // Return a grid of boxes, and a button
  return (
    <main>
      <section className="grid">
        {createGrid()}
      </section>
      <button type="button~" onClick={switchBackground}>
        Switch background
      </button>
    </main>
  );

}

const node = document.getElementById('root');
const root = ReactDOM.createRoot(node);
root.render(<Example />);
.grid { width: 100px; display: grid; grid-template-columns: 50px 1fr; gap: 2px; margin-bottom: 1rem;}
.box { width: 50px; aspect-ratio: 1; }
.red { background-color: red; }
.yellow { background-color: yellow; }
button:hover { cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
<div id="root"></div>

© www.soinside.com 2019 - 2024. All rights reserved.