[英]Dynamically adding children of arbitrary types to React components
我正在使用react-art制作一個小應用,其中用戶可以在運行時添加/刪除許多不同的形狀。
下面概述了我的想象方式。 注意:ES6語法。
頂層畫布,帶有表示形狀及其當前狀態(例如位置)的對象的列表:
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組件的子代數量和類型是動態的。 幾乎感覺就像我通過將子組件作為道具傳遞來與React方法作斗爭,但我想不出另一種方法。
我的問題是,慣用的React方法是什么? 有沒有更好的方法來實現我要完成的任務?
我希望這不是討論問題!
我認為您的方式是React的方式,基於此React文檔 :
render: function() {
var results = this.props.results;
return (
<ol>
{results.map(function(result) {
return <li key={result.id}>{result.text}</li>;
})}
</ol>
);
}
為此,您必須鍵入子元素,例如vkurchatkin說:
當React調和帶鍵的子代時,它將確保所有帶鍵的子代都將重新排序(而不是破壞)或銷毀(而不是重用)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.