【发布时间】:2019-07-14 13:43:42
【问题描述】:
我有一个组件 CreateOCSServiceForm 从它的渲染方法调用另一个组件 ListPage。这个ListPage 期望从其名为ListComponent 的属性中得到一个名为NodeList 的组件,而NodeList 期望从其名为Row 的属性中得到一个组件NodeTableRow,就像这样-
//Getting called from NodeList's attribute
const NodeTableRow: React.FC<NodeTableRowProps> = ({ obj: node, index, key, style, customData }) => {
return (
<TableRow index={index} trKey={key} style={style}>
<td data-key="0" className="pf-c-table__check" role="gridcell">
<input type="checkbox" checked={false}
onChange={(e) => { onSelect(e, e.target.checked, index, node) }}
/>
</td>
<TableData>
---
</TableData>
<TableData>
---
</TableData>
<TableData>
----
</TableData>
<TableData>
----
</TableData>
</TableRow>
);
};
//Getting called from ListPage's attribute
const NodesList = props => <Table customData={props.data} {...props} Row={NodeTableRow} onSelect={onSelect} />;
//main component which is calling ListPage
export const CreateOCSServiceForm: React.FC<CreateOCSServiceFormProps> = (props1) => {
const title = 'Create New OCS Service';
const [error, setError] = React.useState('');
const [inProgress, setProgress] = React.useState(false);
const [rowData, setRowData] = React.useState(null);
const onSelect = (event, isSelected, virtualRowIndex, rowData1) => {
console.log(rowData1, 'customData');
console.log('isSelected', isSelected, 'virtualRowIndex', virtualRowIndex, 'rowData', rowData1);
rowData[virtualRowIndex].selected = true;
setRowData(rowData);
};
return (
<ListPage kind={NodeModel.kind} showTitle={false} ListComponent={NodeList} />}
)
}
问题是 NodeList 和 NodeTableRow 组件必须访问在 CreateOCSServiceForm 组件上定义的 onSelect 方法,但是我应该如何向它们公开这个 onSelect 方法。不想让onSelect 方法全局化,因为我必须在其中使用 CreateOCSServiceForm` 状态。我不能修改 NodeList 和 ListPage 组件,它在我的代码库中的现有组件,修改它会导致破坏其他页面。我们需要在 NodeList 组件中传递 OnSelect 属性的功能。
任何指导将不胜感激。提前致谢
【问题讨论】:
-
将回调作为属性传递...我从未见过有人将组件作为道具传递,您可以尝试使用子组件...
-
@DennisVash 我无法将 NodeList 和 ListPage 组件修改为其现有组件,更改它可能会导致其他页面中断。
-
@DennisVash 将 Component 作为 prop 传递并没有错,它相当于 Strategy Pattern,即使 Render Props (children as a function) 在 React 中更常见,用例为 2模式可以不同
标签: javascript reactjs typescript react-hooks