gpt4 book ai didi

javascript - 如何避免React中3个类似按钮的代码重复?

转载 作者:行者123 更新时间:2023-12-03 22:24:30 26 4
gpt4 key购买 nike

我有3种按钮,分别代表3种不同的语言,

用户可以选择显示哪种语言的文本:

  • “德国德语”
  • “法国法语”
  • “英语”
  • // This is state of component:
    state = {
    translationOptions: {
    german: false,
    french: false,
    english: true
    }
    };

    // This is function which change the language

    <button
    className={`doc-translation-btn ${german ? 'active-background-color' : ''}`}
    onClick={() => this.changeDocumentLanguage('german')}
    >
    DE
    </button>

    <button
    className={`doc-translation-btn ${french ? 'active-background-color' : ''}`}
    onClick={() => this.changeDocumentLanguage('french')}
    >
    FR
    </button>

    <button
    className={`doc-translation-btn ${english ? 'active-background-color' : '' }`}
    onClick={() => this.changeDocumentLanguage('english')}>
    EN
    </button>

    如何优化此代码?

    最佳答案

    const langs = [{name: 'German', abbr: 'GE'}, {name: 'French', abbr: 'FR'}, 
    {name: 'English', abbr: 'EN'}]


    //// Assuming React Stateful Component

    state = {
    translationOption: '' //Will be of of German, French, or English on state change
    }

    ////

    render() {
    return (
    <div>
    {langs.map(({ name, abbr }) => (
    <button
    className={`doc-translation-btn ${name ===
    this.state.translationOption ? 'active-background-color' : '' }`}
    onClick={() => this.setState({ translationOption: name })>
    {abbr}
    </button>
    )}
    </div>
    )
    }

    注意:如果您想在状态下使用单独的 bool(boolean) 属性(无论嵌套还是其他)来处理适用的翻译语言,则需要考虑在状态处理程序方法中将其他属性设置为true时将其他属性切换为false的情况。 (假设一次只能应用一种翻译)。这样的方法可以工作:
      handleLangChange = selectedLang => {
    const { translationOptions: oldOpts } = this.state;
    const translationOptions = Object.keys(oldOpts).reduce((acc, cur) => {
    return { ...acc, [cur]: cur === selectedLang };
    }, {})

    this.setState({ ...this.state, translationOptions });
    }

    关于javascript - 如何避免React中3个类似按钮的代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57010046/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com