您好,我必须将数组作为道具传递给函数组件。
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>
但它会被转换为子组件中的对象。请看渲染函数。当我将数组作为{...figures}传递时,我没有在FBS组件中以数组的形式获取它,这是因为我不能对它运行映射函数。而当我将它作为figures={figures}传递时,我会得到一个数组。我想将它作为{...figures}传递。
请帮帮忙
为了更好的理解,请看我的代码。here
发布于 2019-03-22 22:13:15
您需要额外的对象,该对象将具有一对键和值,它们将被解构为React组件的props。
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,因此出现了错误。
发布于 2019-03-22 22:41:56
您可以使用类似以下内容:
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;https://stackoverflow.com/questions/55301315
复制相似问题