javascript - 向 React 组件动态添加任意类型的子组件

标签 javascript reactjs

我正在使用react-art制作一个小应用程序,用户可以在运行时添加/删除许多不同的形状。

我想象的这样做的方式概述如下。 注意:ES6 语法。

顶级 Canvas ,包含表示形状及其当前状态(例如位置)的对象列表:

class Canvas extends React.Component {

  constructor(props) {
    super(props); // includes list of shapes
  }

  render() {
    return (
      <Surface>
        // my shapes here
      </Surface>
    );
  }
}

许多不同形状的 React 组件:

class SimpleShape extends React.Component {

  constructor(props) {
    super(props); // includes e.g. position of shape
  }

  render() {
    <Circle />
    <Rectangle />
  }
}

我正在考虑在 Canvas 组件中执行类似的操作来渲染形状:

render() {
  return (
    <Surface>
      this.props.shapes.map(function(shape) {
        return React.createElement(shape.component, shape.props);
      });
    </Surface>
  );
}

我一直找不到 React 组件的子组件的数量和类型是动态的示例。感觉就像我在通过将子组件作为 props 传递来对抗 React 方式,但我想不出另一种方法。

我的问题是,React 的惯用方式是什么?有没有更好的方法来实现我想要做的事情?

我希望这不是一个太多的讨论问题!

最佳答案

我认为你的方式是React的方式,基于此React documentation :

  render: function() {
    var results = this.props.results;
    return (
      <ol>
        {results.map(function(result) {
           return <li key={result.id}>{result.text}</li>;
        })}
      </ol>
    );
  }

为此,您必须为子元素设置键,就像 vkurchatkin 所说:

When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).

关于javascript - 向 React 组件动态添加任意类型的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30163985/

相关文章:

javascript - 如何使用传单 map 创建带有数字的热图?

javascript - 使用 jQuery 和 php 执行两个任务

javascript - 如何使用 React js 创建加载旋转器

javascript - React DIV动态布局算法创建盒中盒 View

reactjs - 如何在 React Router Link 组件中添加动态代码

javascript - 我如何使用 react 路由器传递重定向参数?

javascript - 保留 d3 中鼠标悬停功能中状态的颜色

javascript - 用户个人资料页面 - PHP

javascript - Angular.js - 在指令中设置 ng-pattern 时 ngModel 值未定义

javascript - React 不会将多个获取的 API 渲染到 DOM