reactjs 为什么我的React函数组件在更改(布尔)状态属性值时无法重新呈现?

laik7k3q  于 2023-05-06  发布在  React
关注(0)|答案(1)|浏览(113)

我有一个简单的React组件,它呈现一个div,它是一个2行2列的网格容器。它还呈现一个按钮。
我有一个JSX数组,用于在网格中放置四个红色背景的div。
我有另一个JSX数组,用于四个黄色背景的div,当我单击按钮时,我想进入网格而不是红色的。
为了强制重新呈现,我正在更改按钮的onClick处理程序中的state属性的值。
问题是,当我点击按钮时,网格中的方块不会从红色变为黄色。红色的还在那里。
下面是我的代码:

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

                                 }
esyap4oy

esyap4oy1#

与其有两组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>

相关问题