[英]In React, how do I know which parent component rendered a child component?
I'm making a table component that I want to be used across two pages, but I want one page to show two columns and the other page to not.我正在制作一个表格组件,我想在两页中使用它,但我希望一页显示两列,另一页不显示。 I'd like to make a gate inside the component that checks what the parent component is and changes it's render based on that.
我想在组件内部创建一个门来检查父组件是什么,并根据它更改它的渲染。 Is this possible?
这可能吗?
EX: of what I'd like the table to look like EX:我希望桌子看起来像什么
const EventTable = ({ events }) => (
<Box>
<TableBody>
{events.map(
({
amount,
created,
disappearingColumnA,
id,
}) => (
<TableRow key={id}>
<TableCell padding="small" className="created-cell">
<Small>{formatDateStandard(created)}</Small>
</TableCell>
<TableCell padding="small" className="amount-cell">
<Small>{centsToDollarsWithSign(amount)}</Small>
</TableCell>
{/* Relevant Code */}
{!isChildOfPageA && (
<TableCell padding="small" className="disappearingColumnA-cell">
<Small>{centsToDollarsWithSign(disappearingColumnA)}</Small>
</TableCell>
)}
</TableRow>
),
)}
</TableBody>
</Box>
)
you can create functional component Table which will create columns and rows dynamicaly according to passed data.您可以创建功能组件表,它将根据传递的数据动态创建列和行。 But before passing data you should prepare it in parent component in a proper format.
但是在传递数据之前,您应该以适当的格式在父组件中准备它。
here is simple example of one of my componente(based on Semantic-ui React):这是我的一个组件的简单示例(基于 Semantic-ui React):
return (
<Table celled>
<Table.Header>
<Table.Row>
{
columnNames.map(columnName => {
return <Table.HeaderCell key={columnName}>
{columnName}
</Table.HeaderCell>
})
}
</Table.Row>
</Table.Header>
<Table.Body>
{
tableData.map((item) => {
return <Table.Row key={item.userId}>
<Table.Cell width={2}>{item.firstName}</Table.Cell>
<Table.Cell width={2}>{item.lastName}</Table.Cell>
<Table.Cell width={3}>{item.email}</Table.Cell>
<Table.Cell width={3}>{item.telephone}</Table.Cell>
<Table.Cell>
<Button>
Info
</Button>
<Button>
Delete
</Button>
</Table.Cell>
</Table.Row>
})
}
</Table.Body>
</Table>
This table I needed in different pages.我在不同的页面中需要这张表。 So I divided it and pass separate column names and data.
所以我把它分开并传递单独的列名和数据。 You can do similar thing - use such component in any page and pass from parent 2 data objects: 1 object\array with column names 2 object with data to fill table
您可以做类似的事情 - 在任何页面中使用此类组件并从父 2 个数据对象传递:1 个对象\数组,列名 2 object,数据填充表
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.