如何在状态中将一个值设置为“ on”,将其他所有值设置为“ off”?

时间:2019-08-01 11:49:16

标签: javascript reactjs

我正在尝试设置我的应用程序的状态,其中状态对象中有3个键值对。我只想将一个设置为“开”,其余设置为“关”。

onMenuClick = (leafName) => {

        this.setState(Object.assign({}, {
            news: "off",
            tournament: "off",
            register: "off",
        }, { leafName: "on" }))

    }

import React from 'react'
import './Leaf.css'
import { Link } from 'react-router-dom'




const Leaf = ({ leafName, state, onMenuClick }) => {

    return (

        <div onClick={() => onMenuClick(leafName)} className={`leaf ${state}`}>
            <Link className="a" to={leafName}>{ leafName.toUpperCase() }</Link>
        </div>



    )

}


export default Leaf

import React from 'react'
import './Menu.css'
import Leaf from '../Leaf/Leaf'



class Menu extends React.Component {

    constructor() {
        super()

        this.state = {
            news: "off",
            tournament: "off",
            register: "off",
        }
    }

    onMenuClick = (leafName) => {

        this.setState(Object.assign({}, {
            news: "off",
            tournament: "off",
            register: "off",
        }, { leafName: "on" }))

    }

    render() {

        return (
            <div className="menu">
                <Leaf onMenuClick={this.onMenuClick} leafName="news" state={this.state.news} />
                <Leaf onMenuClick={this.onMenuClick} leafName="tournament" state={this.state.tournament} />
                <Leaf onMenuClick={this.onMenuClick} leafName="register" state={this.state.register} />
            </div>
        )

    }

}
export default Menu

应该是菜单导航。如果我单击其中之一,则应激活我单击的那一项,而其余应禁用。而且它不起作用。

2 个答案:

答案 0 :(得分:1)

不要根据情况存储状态。超出您的需要管理。

存储已打开的那个,然后在需要时将当前的叶子名称与其进行比较。例如

onMenuClick = (leafName) => {
    this.setState(Object.assign({}, {
        on: leafName,
    }));
};

const Leaf = ({ leafName, state, onMenuClick }) => {
    return (
        <div onClick={() => onMenuClick(leafName)} className={`leaf ${leafName === state.on ? "on" : "off"}`}>
            <Link className="a" to={leafName}>{ leafName.toUpperCase() }</Link>
        </div>
    )
}

答案 1 :(得分:0)

将leafName放在setState的方括号中:

{ [leafName]: “on” }