reactjs - 选中反应输入复选框
问题描述
我为我的应用程序使用了 React-redux 和样式化组件。我将我的初始状态主题存储为一个明暗的字符串。然后我在我的根应用程序中连接我的样式组件初始浅色主题和深色主题。当我使用选择选项时,我的忧郁情绪很好,但是当我使用输入复选框时,它不起作用。我从未使用过输入复选框,在阅读了几个示例后,我使用checked
并放置了我的初始主题(来自我的 redux 商店),然后在我的 handleChange 中我做了,如果event target has dark
然后调度黑暗主题。但是那个句柄没有发生任何变化。不知道我在做什么错。
这是我的切换组件
import React, { useState } from 'react';
import styled from 'styled-components';
import { useDispatch, useSelector } from 'react-redux';
import { appSettings } from '../../state/appSettings';
import { TRootState } from '../../state/index';
export default function Toggle({ }: IProp) {
const dispatch = useDispatch();
const { "appSettings": appSettingState } = useSelector((state: TRootState) => state);
const { theme } = appSettingState || {};
console.log(theme); // inital state which is "light".
return (
<>
{/* This input checkbox does not work */}
<CheckBoxWrapper>
<CheckBox
onChange={(e) => { // This function does not work
e.target.value === `dark` ?
dispatch(appSettings?.actions?.enableDarkTheme()) :
dispatch(appSettings?.actions?.enableLightTheme());
}}
id="toggleSwitch"
type="checkbox"
Checked={theme === `light`}
/>
<CheckBoxLabel htmlFor="toggleSwitch" />
</CheckBoxWrapper>
<br></br>
{/* THIS SELECT OPTIONS WORK FINE. AND I CAN GET DARK AND LIGHT THEME */}
<h2>Theme</h2>
<select
name="theme"
id="theme-select"
value={theme}
onChange={(e) => {
if (e.target.value === `dark`) {
dispatch(appSettings?.actions?.enableDarkTheme());
} else {
dispatch(appSettings?.actions?.enableLightTheme());
}
}}
>
<option value="dark">Dark</option>
<option value="light">Light</option>
</select>
</>
);
}
// This toogle input styled
const CheckBoxWrapper = styled.div`
position: fixed;
top:10px;
right:10px;
`;
const CheckBoxLabel = styled.label`
position: absolute;
top: 0;
left: 0;
width: 42px;
height: 26px;
border-radius: 15px;
background: #bebebe;
cursor: pointer;
&::after {
content: "";
display: block;
border-radius: 50%;
width: 18px;
height: 18px;
margin: 3px;
background: #ffffff;
box-shadow: 1px 3px 3px 1px rgba(0, 0, 0, 0.2);
transition: 0.2s;
}
`;
const CheckBox = styled.input`
opacity: 0;
z-index: 1;
border-radius: 15px;
width: 42px;
height: 26px;
&:checked + ${CheckBoxLabel} {
background: #4fbe79;
&::after {
content: "";
display: block;
border-radius: 50%;
width: 18px;
height: 18px;
margin-left: 21px;
transition: 0.2s;
}
}
`;
解决方案
推荐阅读
- google-apps-script - Google Apps 脚本 - 匹配 2 个字符串
- c# - 如何将包含 SqlConnection 对象的类固定到内存中
- python - UnboundLocalError:分配前引用了局部变量'print'?
- python - 动态过滤掉 sqlalchemy 中的数据
- django - 什么是浅键变换
- r - 在 R 数据框中选择具有两个不同概率的行
- sql - 我应该如何设计一个表格,其中一行可以根据行的类型有不同的列?
- .net-core - 什么是基于微服务的架构中的上游和下游服务?
- image - 上传图片生成特效视频
- ajax - AJAX 默认配置