javascript - 无法将属性添加到函数内的对象
问题描述
我正在尝试向对象插入属性,这是代码
import React from 'react';
import { Link } from 'react-router-dom';
const Question = () => {
let active;
const handleClick = (iconName) => {
active = {};
active[iconName] = true;
};
console.log(active.isHome); // undefined
return (
<Link to='/'>
<div
className={`center ${active.isHome && 'active'}`}
onClick={() => handleClick('isHome')}
>
<Home className='navItem' />
</div>
</Link>
);
};
export default Question;
以上active.isHome
回报undefined
。这对我来说似乎是一个意外的行为。我可以做些什么来插入isHome: true
对象active
以及为什么没有为 active 赋值?
解决方案
从我从问题中理解的解决方案。如果“ showHome.active?.isHome ”为真,则活动类使背景变为绿色,并且我使用可选链接来忽略活动内部的不存在属性,当页面最初加载时
import React, { useState } from 'react';
const initialState = {
active: {},
};
function App() {
const [showHome, setShowHome] = useState(initialState);
const bgChange = (iconName) => {
let active = {};
active[iconName] = true;
setShowHome({ active });
};
console.log(showHome, '<>?', showHome.active?.isHome && 'active');
return (
<div className="body">
<button onClick={() => bgChange('isHome')}>make active </button>
<div className={`center ${showHome.active?.isHome && 'active'}`}>
<h1>hi visible in Green</h1>
</div>
</div>
);
}
推荐阅读
- python - 网页抓取表不返回任何数据
- python-3.x - 如何在Python pandas中按条件列排序
- jquery - 如何使用选择删除自定义样式
- python - wxPython WebView:如何重新加载错误?
- apache-kafka-streams - 使用 STATE_CLEANUP_DELAY_MS_CONFIG
- karate - 空手道 -Gatling:无法更新模拟类名称
- c# - 如何将 ObservableCollection 绑定到 XAML 中的 IList 属性?
- spring - SQL 错误:23503,SQLState:23503 在 SpringBoot 2.1.4.RELEASE 应用程序中
- scala - 如何在需要具体类型的情况下使用具有存在类型的变量?
- php - 登录主页后如何解决akeneo仍然加载?