Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 动态地将道具应用于组件_Reactjs - Fatal编程技术网

Reactjs 动态地将道具应用于组件

Reactjs 动态地将道具应用于组件,reactjs,Reactjs,我正在循环中渲染组件。我想在屏幕上随机放置它们,所以我考虑使用一个函数来渲染它们。该函数应负责查找随机x、y坐标并将其应用于渲染组件。但是我该怎么做呢 App.js 类应用程序扩展组件{ //这些形状是SFC返回的``元素 状态={ 形状:[,,] }; randomShapeIndex=correctShapeIndex=>{ const max=this.state.shapes.length-1; 返回Math.floor(Math.random()*(max+1)); }; render

我正在循环中渲染组件。我想在屏幕上随机放置它们,所以我考虑使用一个函数来渲染它们。该函数应负责查找随机x、y坐标并将其应用于渲染组件。但是我该怎么做呢

App.js

类应用程序扩展组件{
//这些形状是SFC返回的``元素
状态={
形状:[,,]
};
randomShapeIndex=correctShapeIndex=>{
const max=this.state.shapes.length-1;
返回Math.floor(Math.random()*(max+1));
};
render(){
const{shapes}=this.state;
const selectedShapes=[];
常数numberOfShapes=5;
随机指数;
for(设i=0;i
这是一个随机的元素(
)
)}
);
}
//这是我想要创建x,y坐标并作为props`x`和`y应用于元素的函数`
PositionElement随机=元素=>{
元素={…元素};
返回元素;
};
}
导出默认应用程序;
Element.js

import React,{Component}来自“React”;
类元素扩展组件{
render(){
const{shape,x,y}=this.props;
返回(
{shape}
);
}
}
导出默认元素;
这是您的功能:

positionelement随机=元素=>{
const randomPositionElement=React.cloneElement(元素,{x:1,y:2});
返回随机位置元素;
};
另一方面,将
形状
逻辑与定位分离显然更好

大概是这样的:

positionelement随机=元素=>{
const randomPositionElement=React.cloneElement(元素,{x:1,y:2});
返回({element});
}; 
Element.js

import React,{Component}来自“React”;
类元素扩展组件{
render(){
const{shape,x,y}=this.props;
返回(
{shape}
);
}
}
导出默认元素;
PositionWrapper.js

import React,{Component}来自“React”;
类包装器扩展组件{
render(){
const{children,x,y}=this.props;
返回(
{儿童}
);
}
}
导出默认位置包装器;

它可能需要一个额外的
div
,但会带来更干净的体系结构。

以下是您可以做的。为每个元素使用并生成一个新实例

类应用程序扩展了React.Component{
//这些形状是SFC返回的``元素
建造师(道具){
超级(道具);
此.state={
形状:[,,]
};
}
randomShapeIndex=correctShapeIndex=>{
常数max=10;
返回Math.floor(Math.random()*(max+1));
};
render(){
const{shapes}=this.state;
const selectedShapes=[];
常数numberOfShapes=5;
随机指数;
for(设i=0;i
这是一个随机的元素(
)
)}{" "}
);
}
//这是我想要创建x,y坐标并作为props`x`和`y应用于元素的函数`
PositionElement随机=元素=>{
返回反作用克隆元素(元素);
};
}
类元素扩展了React.Component{
render(){
const{shape,x,y}=this.props;
返回(
{shape}{”“}
);
}
}
类。组件{
render(){
返回圈;
}
}
类Square扩展了React.Component{
render(){
返回广场;
}
}
ReactDOM.render(,document.querySelector(“#root”)

如果使用
是否也需要克隆元素并在其上放置x和y道具?否。在这种情况下,您将形状包裹在另一个div中,该div已定位。我已经更新了答案。