嗨,我必须将数组作为道具传递给功能组件。
import React from "react";
import { render } from "react-dom";
const App = () => {
const FBS = ({ figures }) => {
console.log(typeof figures);
return figures.map((item, key) => <p key={key}>{item.description}</p>);
};
const figures = [
{
config: 112,
description: "description text 1"
},
{
config: 787,
description: "description text 2"
}
];
return (
<div>
{/* <FBS {...figures} /> */}
<FBS figures={figures} />
</div>
);
};
render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<body>
<div id='root' />
</body>
但它被转换为子组件中的对象。请查看渲染功能。当我将数组作为{...数字}传递时,我不会在FBS组件中将其作为数组,因为我无法在其上运行地图功能。而当我将其作为数字= {数字}传递时,我得到一个数组。我希望将其作为{...数字}传递给我。
请帮忙
请查看我的代码以便更好地理解。 here
你需要有一个额外的对象,它将具有一对键和值,它们将被解构为你的props
到React组件。
const props = {
figures, // shorter way of writing figures: figures
// Any other objects you'd like to pass on as props
}
然后,你可以这样做:
<FPS {...props} />
基本上你只能在React组件中对一个对象进行解构,因为那时解构对象的键值对将成为组件的props
。
为了更好地理解,
const arr = [{ a: 'a'}]
{...arr}
会给:
{
0: {a: 'a'}
}
因为0
是关键,因为它是一个数组而不是一个对象,所以你真正做的是传递一个名为0
而不是figures
的支柱,figures
是undefined
,因此错误。
你可以使用这样的东西:
import React from "react";
import Figure from './Figure';
import { render } from "react-dom";
const App = () => {
const figures = [
{
config: 112,
description: "description text 1"
},
{
config: 787,
description: "description text 2"
}
];
return (
<div>
{
figures.map((figure, key) => {
return <Figure key={key} {...figure}/>
})
}
</div>
);
};
render(<App />, document.getElementById("root"));
并创建一个名为Figure的组件,如下所示:
import React from "react";
const Figure = (props) => {
return (
<div>
<p>{props.description}</p>
<p>{props.config}</p>
</div>
);
};
export default Figure;