javascript - 在自定义点击时反应条件样式
问题描述
我试图在onClick
触发事件时更改一个类,调用我的函数并且它似乎正在工作,但是该类不会更新渲染,这是我的代码:
import React from 'react';
const Something = props => {
let opened = false;
const toggle = () => {
opened = !opened;
};
return (
<div className={opened ? 'some-class opened' : 'some-class'}>
<div className="some-inner-class" onClick={toggle}>
...content
</div>
</div>
);
};
export default Something;
我只想能够在点击事件触发时更改样式。
解决方案
我对你的建议是在这种情况下使用反应钩子,我的意思是,像这样,我已经用我的建议更新了你的代码;希望能帮助到你;
import React, { useState } from 'react';
const Something = props => {
// ***because this doesn't exist in a function component and we'd want to persist this value of opened between function call, a react hook in a function component will be ideal in your case.
//let opened = false;
// *suggestion as per react documentation: useState hook lets us keep local state in a function component
const [opened, setOpened] = useState(false);
// ***you don't really need this part, see my approach in second div of return
// const toggle = () => {
// opened = !opened;
// };
return (
<div className={opened ? 'some-class opened' : 'some-class'}>
<div className="some-inner-class" onClick={() => setOpened(true)}>
<p>Click me</p>
</div>
</div>
);
};
export default Something;
推荐阅读
- javascript - 在这个 Twilioquest 练习中我做错了什么?(sortOrder.js - JavaScript 开始)
- android - 未处理的异常类型'String'不是'index'的'int'类型的子类型
- python - 如何使用 Tensorflow 在多个设备上并行执行 TF 图的独立分支?
- flutter - 如何在 DropdownButton 周围绘制边框,如 TextFormField 边框?
- tableau-api - Tableau 中的 AND/OR 语句
- facebook - Facebook Pixel Error OAuth "Facebook Platform" "invalid_token" "验证访问令牌时出错:用户尚未授权应用程序
- javascript - 出现错误 - 错误:在 .env.local 文件中写入 EPIPE
- jquery - 使用 JQuery 到 wordpress 管理页面 wp-admin
- javascript - 跨域请求被阻止:同源策略不允许读取位于 ... 的远程资源:CORS 标头“Access-Control-Allow-Origin”缺失
- uart - Raspberry Pi4 Uart 接收缓冲区溢出