问题描述
一般来说是 React 和 js 的新手,所以这可能是一个愚蠢的问题,但我无法解决。
export interface TableViewContainerProps {
header: WorthSummaryContainerProps
content: TableViewRowProps[]
}
export const TableViewContainer = (props: TableViewContainerProps) => {
console.log('content type is ',typeof(props.content))
console.log('content is ',props.content)
return (
<div id="tableview-container">
<div id="tableview">
<TableViewHeader {...props.header}/>
<TableViewContentList {...props.content} />
<div id="tableview-footer">
</div>
</div>
</div>
)
}
所以当我打印它时它是一个对象数组,一切都很好。
TableViewContentList
获取内容作为道具:
export const TableViewContentList = (props: TableViewRowProps[]) => {
console.log('type of TableViewContentList props is: ',typeof(props),props)
const tableViewContents = props.map((row) => console.log('row'))
return (
<div id="tableview-content-list">
{tableViewContents}
</div>
)
}
所以当我在这里打印它时,它不再是一个对象,而是在 .map
处中断。有人可以帮我吗?我觉得我错过了一些小事。
解决方法
Spread syntax (...) 将在您将其应用于对象内的数组时为您提供一个对象。
type TableViewRowProps = number;
interface TableViewContainerProps {
content: TableViewRowProps[]
}
const props = {content: [1,2,3]}
const b = {...props.content}
console.log(b) // { "0": 1,"1": 2,"2": 3 }.
所以 TableViewContentList
获得了道具:props[0]
、props[1]
和 props[2]
,这是错误的。
传递给组件的所有属性都将附加在 props
中,这就是您获得对象的原因。 props
将始终是一个对象。所以你最好像这样传递 content
:
<TableViewContentList {...props} />
或者这个:
<TableViewContentList content={props.content} />
然后你可以将它映射到行:
export default function TableViewContentList(props: { content: TableViewRowProps[] }) {
const tableViewContents = props.content.map((row) => console.log('row'));
return <div id="tableview-content-list">{tableViewContents}</div>;
}