首页 > 解决方案 > 无法将属性添加到函数内的对象

问题描述

我正在尝试向对象插入属性,这是代码

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 赋值?

标签: javascriptreactjsfunctionobject

解决方案


从我从问题中理解的解决方案。如果“ 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>
    );
}

推荐阅读