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

时间:2019-07-12 15:34:23

标签: javascript reactjs

我有3个用于3种不同语言的按钮,

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

  1. “德国德语”

  2. “法国法语”

  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>

如何优化此代码?

4 个答案:

答案 0 :(得分:5)

def respond_to?(method_name, include_private = false)
  if method_name.to_s == 'unique_session_id' && self.status == 'mystatus'
    false
  else
    super
  end
end

注意:如果您想在状态下使用单独的布尔属性(无论嵌套还是其他)来处理适用的翻译语言,则需要考虑将其他属性切换为false的情况。在状态处理程序方法中设置为true(假设一次只能应用一种翻译)。这样的方法可以工作:

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>
  )
}

答案 1 :(得分:4)

您可以创建函数renderButtons,在其中创建对象数组,然后将其map()设置为按钮。

renderButtons(){
   let btns = [
        {name: 'german', short: 'DE'}
        //... same for others.
   ]
   return btns.map(({name, short}) => (
      <button
    className={`doc-translation-btn ${this.state.translationOptions[name] ? 'active-background-color' : ''}`}
    onClick={() => this.changeDocumentLanguage(name)}
  >
     {short}
  </button>
   ))
} 

render()方法中,只需在需要按钮的地方调用此方法即可。

render(){
    return (
       <div>{this.renderButtons()}</div>
    )
}

答案 2 :(得分:1)

使用数组:

const langDef = [
  { key: 'german', label: 'DE' },
  ...
]

const buttons = langDef.map(({ key, label })=>
  <button
    className={`doc-translation-btn ${this.state.translationOptions[key] ? 'active-background-color' : ''}`}
    onClick={() => this.changeDocumentLanguage(key)}
  >
     {label}
  </button>
)

return <div className="my-awesome-language-selector">{buttons}</div>

答案 3 :(得分:1)

根据用例,您还可以为此创建一个新组件:

 const LangButton = ({ active, name, abbr }) =>
  <button className={`doc-translation-btn ${active ? 'active-background-color' : ''}`}  onClick={() => this.changeDocumentLanguage(name)}>{abbr}</button>;

 return <div>
   <LangButton active={german} name="german" abbr="DE" />
   ...
 </div>;