javascript - 切换状态组件的未定义 e.target.name
问题描述
尝试使用 useState 设置切换/开关列表时遇到错误。所有初始状态都正常工作并且页面呈现,但是当我单击任何切换时,我收到以下错误:TypeError:无法读取未定义的属性“名称”。我只需要设置我点击的那个的状态。感谢您提前提供任何帮助。
import React, {useState} from 'react'
import Dashboard from './Dashboard'
import Switch from "react-switch"
import styles from './Settings.module.scss'
const Settings = () => {
const [privacyToggles, setprivacyToggles] = useState({
newContentNotification: false,
newCommentSubscribed: true,
newCommentCommented: true,
publicDonationInfo: false
})
const handleToggleChange = (e) => {
setprivacyToggles({
...privacyToggles,
[e.target.name]: !privacyToggles[e.target.name]
})
}
return (
<>
<Dashboard />
<div className="section">
<div className="container">
<h2 className="title is-4">Settings</h2>
<h3 className="title is-5">Privacy Settings</h3>
<div className="columns">
<div className={styles.toggleList + " column is-full"}>
<label className={styles.toggleLabel}>
<Switch
onChange={handleToggleChange}
checked={privacyToggles.newContentNotification}
name="newContentNotification"
/>
<span className={styles.toggleText}>Receive notification of new content published on the website</span>
</label>
<label className={styles.toggleLabel}>
<Switch
onChange={handleToggleChange}
checked={privacyToggles.newCommentSubscribed}
name="newCommentSubscribed"
/>
<span className={styles.toggleText}>Receive notification when somebody adds a comment to an article I am subscribed to</span>
</label>
<label className={styles.toggleLabel}>
<Switch
onChange={handleToggleChange}
checked={privacyToggles.newCommentCommented}
name="newCommentCommented"
/>
<span className={styles.toggleText}>Receive notification when somebody adds a comment to an article I commented on</span>
</label>
<label className={styles.toggleLabel}>
<Switch
onChange={handleToggleChange}
checked={privacyToggles.publicDonationInfo}
name="publicDonationInfo"
/>
<span className={styles.toggleText}>Publish information about my donations and make them public on my profile</span>
</label>
</div>
</div>
</div>
</div>
</>
)
}
导出默认设置
解决方案
新 好的,我已经编辑了答案。
const handleToggleChange = (...args) => {
setprivacyToggles({
...privacyToggles,
[args[2]]: args[0]
});
};
WRONG
react-switch
旨在通过onChange
事件获取相反的值。
你可以在这里查看。
您应该构建自己的切换组件以获得所需的结果。
推荐阅读
- python - 异常后如何在python中“重新填充”工作队列?
- javascript - 有没有办法使用 map() 或 forEach() 在 reactjs 中使用从我的后端加载的 json 数据设置 Tabs 内容?
- angular - 如何从 Safari 中的代码触发点击调用
- laravel - Laravel 查询不允许我查询内部的位置或位置
- node.js - 在 firebase 函数中调用另一个 api
- python - 如何使用python将一串单词放入一列
- php - 获取后的Laravel分页
- reactjs - ? 在 React.js 上创建数据后,由于未知原因出现在 url 上
- r - R Vegan 包:从 permanova (adonis) 中排除 NA 值
- django - Django 模型中不允许同一个表有两个 OneToOneFields