动态添加 children 任意类型到 React 组件
Dynamically adding children of arbitrary types to React components
我正在使用 react-art 制作一个小应用程序,用户可以在运行时 added/removed 制作许多不同的形状。
下面概述了我想像的方法。 注意:ES6语法。
Top-level canvas,其中 objects 的列表表示形状及其当前状态(例如位置):
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 组件的 children 的数量和类型是动态的。几乎感觉我通过传入 child 组件作为道具来反对 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).
我正在使用 react-art 制作一个小应用程序,用户可以在运行时 added/removed 制作许多不同的形状。
下面概述了我想像的方法。 注意:ES6语法。
Top-level canvas,其中 objects 的列表表示形状及其当前状态(例如位置):
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 组件的 children 的数量和类型是动态的。几乎感觉我通过传入 child 组件作为道具来反对 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).