kasom:
私は特定の瞬間に描画オブジェクトを正確に知らなくてもKonvaJsの助けを借りて、コンポーネントに反応の配列をレンダリングします。具体的には、ここに私のコードは次のとおりです。
私はレンダリングするリアクトコンポーネントの一つは、wall.js:
class CWall extends React.Component {
render() {
return (
<React.Fragment>
<Rect /*some props*/></Rect>
<Transformer /*some props*/></Transformer>
</React.Fragment>
)
}
}
ボタンがクリックされたときに、他のコンポーネントでは、私は、planmenu.jsをCWallを作成します。
class PlanMenu extends React.Component {
render() {
...
return (
...
<button type="button"
onClick={() => { addObject(
new CWall({
x: 100,
y: 100,
length: 200
}))}}>Wall
</button>
)
}
}
作成されたオブジェクトは、それらを表示する必要があるコンポーネント、planbuilder.jsに渡されます。
import CWall from './objects/wall'
class PlanBuilder extends React.Component {
render() {
const { objects } = this.props
return (
<Stage>
<Layer>
{
objects.map(function(object) {
var ObjectType = object.constructor.name;
/* the following line gives an error to me */
return <ObjectType {...object.props} key={object.id} />;
}, this)
}
</Layer>
</Stage>
);
}
}
指定された行でエラーが発生します:
konvaはタイプとはノードを持たないCWall
ただし、期待どおり、私は1 CWallをレンダリングする場合は、直接、私は画面上にそれを得ます。それはkonvaがCWallオブジェクトをレンダリングすることが可能であるという証拠のように私には思えます。
class PlanBuilder extends React.Component {
render() {
const { objects } = this.props
return (
<Stage>
<Layer>
<CWall x={100} y={100} length={200} />
</Layer>
</Stage>
);
}
}
だから私の質問です:その正確な種類を知らなくても、オブジェクトをレンダリングする適切な方法は何ですか?前もって感謝します。
lavrton:
一般的に、あなたは直接状態にコンポーネントに反応追加しないでください。代わりに、ちょうどあなたのアプリについて、純粋なデータを追加し、ちょうどそのデータからレンダリングします。それはこのようにすることができます:
class PlanMenu extends React.Component {
render() {
...
return (
...
<button type="button"
onClick={() => { addObject({ x: 10, y: 10, type: 'wall' })}}
</button>
)
}
}
import CWall from './objects/wall'
const TYPES = {
'wall' : CWall
};
class PlanBuilder extends React.Component {
render() {
const { objects } = this.props
return (
<Stage>
<Layer>
{
objects.map(function(object) {
const Component = TYPES[object.type];
return <Component {...object} key={object.id} />;
}, this)
}
</Layer>
</Stage>
);
}
}