javascript - 如何在 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'));
解决方案
目前,您的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)}
/>
))}
</>
);
};
推荐阅读
- node.js - 在 AWS 或 GCP 上部署 Node + MongoDB API
- angular - Microsoft Graph 代表用户获取访问权限
- edit - 有没有办法在不更改序列号的情况下编辑 ISO 文件
- swift - Xcode 自动完成:<
> 项目编译时 - django - 如何使用 get_redis_instance 获取当前用户?
- file - 如何使用 CMD 查找包含特定字符串的文件夹?
- python - TensorFlow:为什么我的 Keras 回调监视器值不可用?
- flutter - 如何在 SingleChildScrollView 中使用 Expanded?
- spring-cloud - Spring Cloud 函数和 SQSEvent 触发的 AWS Lambda 函数
- haskell - Haskell 支持哪些多态类型?