我正在使用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/