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

时间:2018-08-13 07:47:16

标签: javascript reactjs

我要根据其满足的条件设置LOGGING = { 'version': 1, 'formatters': { 'simple': { 'format': 'LOG: {levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, }, } } 。按钮目前没有值属性。我该怎么写?我想要这样的value="a"

<button value="a"> One </button>

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

它会像这样:

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

另一种净值方法是:

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