如何在React中动态分配属性

How to assign properties dynamically in React?

本文关键字:动态分配 属性 React      更新时间:2023-09-26

这里有一个函数,它有两个参数:

  1. 我要创建的标记的名称
  2. 具有以下属性的对象

使用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'
})

您正在重新实现现有的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);
  }
});