首页 > 解决方案 > 在反应jsx中的一个元素中实现一组对象作为属性

问题描述

我有一个组件,我想将一个未知的对象数组(长度未知)传递给它,并将其显示为内部输入标记中键和值格式的属性。

<Input 
  type="text"
  label = {"length" + '(' + this.state.package_length_unit + ')'}
  placeholder = "length"
  defaultValue = {this.state.package_length ? this.state.package_length : ''}
  onInputChange = { this.onInputChange }
  attrs = {[{name: 'id',value: 'package_length'},{name: 'apikey',value: 'package_length'}]}
/> 

在组件内部我有这样的东西

<input 
  type = {props.type} 
  ref = {this.inputRef}
  className = {inputClassName}
  disabled = {props.disabled ? 'disabled' : ''}
  defaultValue = {props.defaultValue ? props.defaultValue : ''}
  onChange = {props.onInputChange ? props.onInputChange : e => {}}
  onKeyUp = {this.handleTyping}
  placeholder = {
     props.placeholder ? props.placeholder : ''
  } 
  {...props.attrs} // ??
  // ********* here I want to have ==> 
  // id = 'package_length'
  // apikey = 'package_length'
  // ********* printed
 />

有没有办法做到这一点?提前致谢。

标签: javascriptreactjs

解决方案


{
  ...props.attrs.reduce((prev, curr) => {
    prev[curr.name] = curr.value;

    return prev;
  }, {})
}

推荐阅读