如何在React中动态分配属性?

时间:2015-11-29 09:20:38

标签: javascript reactjs

这是一个有两个参数的函数:

  1. 我要创建的代码的名称
  2. 具有属性
  3. 的对象

    使用 React ,我创建一个组件并将该元素呈现给DOM。问题是我想为元素添加属性,但它不允许循环在元素中设置属性。

    var Element = function(element, properties) {
      var newElement = React.createClass({
        render: function() {
          return (
            React.createElement(element, {}, 'react reuseable')
          );
        }
      });
    
      ReactDOM.render(React.createElement(newElement, null), document.getElementById('content'));
    }
    

    这是创建React元素的函数调用:

    Element('g', {
      id: 'DrawingController.drawingPathCounter ' + '_shape',
      d: 'path',
      fill: 'none',
      stroke: 'Controllers.TemplateController.wireFrameColour_Selected',
      'stroke-width': 1,
      'class': 'drawingpath',
      pathhover: '',
      'vector-effect': 'non-scaling-stroke'
    })
    

1 个答案:

答案 0 :(得分:2)

您正在重新实施现有的React.createElement方法。

您可以将组件的独特道具存储在数组中,然后使用这些道具创建组件列表。

var propsList = [
  { id: 1, d: 'path', fill: 'none' }, 
  { id: 2, d: 'path', fill: 'none' }, 
  { id: 3, d: 'path', fill: 'none' } 
];

var components = propsList.map(function(props) {
  return React.createElement('g', props);
});

var App = React.createClass({
  render: function() {
    return React.createElement('div', null, components);
  }
});

ReactDOM.render(
  React.createElement(App, null),
  document.getElementById('content')
);

如果您希望属性列表是动态的,那么您应该将其存储在组件的状态中。

var App = React.createClass({
  getInitialState: function() {
    return {
      propsList: []
    };
  },
  addProps: function(props) {
    var propsList = this.state.propsList.concat([props]);
    this.setState({ propsList: propsList });
  },
  render: function() {
    var components = this.state.propsList.map(function(props) {
      return React.createElement('g', props);
    });

    return React.createElement('div', null, components);
  }
});
相关问题