首页 > 解决方案 > 如何在 JSX 中动态更新样式

问题描述

useRef()我正在尝试使用React中的钩子在单击每个按钮时更新其单独样式。

现在,当我单击任何按钮时,样式更改总是应用于最后一个呈现的按钮。

我相信这是需要注意的一点,但我很难过。

  const handleClick = () => {
    status.current.style.background = 'green';
  }  

这是完整的部分:

import React, { useRef } from 'react';
import ReactDOM from 'react-dom';
import './index.css';

let background = 'blue';
let controls = [];

const makeControls = () => {
  for (let i = 1; i <= 9; i++) {
    controls.push({active: false});
  }
  return controls;
};

const ControlPanel = () => {
  const status = useRef('blue');
  makeControls();

  const handleClick = () => {
    status.current.style.background = 'green';
  }  

  return (
    <>
      {controls.map((control, i) => (
        <div
          ref={status}
          style={{background: background}}
          className={'box'}
          key={i}
          onClick={() => handleClick()}></div>
      ))}
    </>
  );
};

ReactDOM.render(<ControlPanel />, document.getElementById('root'));

标签: javascriptreactjs

解决方案


目前,您的ref目标仅是最后一项,您应该通过创建一个refs 数组来定位所有控制项。

let controls = [];

const makeControls = () => {
  for (let i = 1; i <= 9; i++) {
    controls.push({ active: false });
  }
  return controls;
};

makeControls();

const ControlPanel = () => {
  const status = useRef([]);

  const handleClick = index => {
    status.current[index].style.background = 'green';
  };

  return (
    <>
      {controls.map((control, i) => (
        <div
          ref={ref => (status.current[i] = ref)}
          style={{ background: `blue`, width: 100, height: 100 }}
          key={i}
          onClick={() => handleClick(i)}
        />
      ))}
    </>
  );
};

编辑分心的雪花-ngp4n


推荐阅读