简体   繁体   English

如何在React中动态添加属性名称和属性值

[英]How to add attribute name and attribute value dynamically in React

I want to set value="a" depending on the condition it meets. 我想根据其满足的条件设置value="a" Button has no value attribute currently. 按钮目前没有值属性。 How do I write this?I want like this <button value="a"> One </button> 我该怎么写?我想要这样的<button value="a"> One </button>

const buttonValues = ["a", "b"]  

const addingValuesToButtons = () => {
   for (var i = 0; i < buttonValues.length; i++) {
      if(buttonValues[i] === "a") {
         //add attribute name and value to first two buttons
      }
      if(buttonValues[i] === "b"){
         //add attribute name and value to first three buttons
      }
   };

   return(
     <div>
      <button> One </button>
      <button> Two </button>
      <button> Three </button>
      <button> Four </button>
     </div>
   )
}
const buttonValues = ["a", "b"]  

const addingValuesToButtons = () => {
   const buttons = [];
   for (var i = 0; i < buttonValues.length; i++) {
      if(buttonValues[i] === "a") {
         buttons.push({attr: 'foo', name: 'bar'});
      }
      if(buttonValues[i] === "b"){
         buttons.push({attr: 'baz', name: 'bar2'})
      }
   };

   return(
     <div>
      {buttons.map(button => {
        return <button attr={button.attr}>{button.name}</button>;
      })}
     </div>
   )
}

It will go like this: 它会像这样:

<button value={this.buttonValues[0] == 'a'?this.buttonValues[0]:null}> One </button>

another netter approach is : 另一种净值方法是:

const buttonValues = [{value:"a",name:"One"}, {value:"b",name:"two"}]  

this.buttonValues.map(value => {<button value={value.value == 'a'? value.value:null}>{value.name}</button>}) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM