如何在反应中从A组件传递值到B组件?



父组件

export interface IInvoiceDetailProps extends StateProps, DispatchProps, RouteComponentProps<{ id: string }> { }
export const InvoiceDetail = (props: IInvoiceDetailProps) => {
useEffect(() => {
props.getEntity(props.match.params.id);
}, []);
const { invoiceEntity } = props

return (
<Row>
<**InvoiceItem** {...props} />
</Row>
);
} 
const mapStateToProps = ({ invoice }: IRootState) => ({
invoiceEntity: invoice.entity,
});
const mapDispatchToProps = { getEntity };
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;
export default connect(mapStateToProps, mapDispatchToProps)(InvoiceDetail);

子组件


export interface IInvoiceItemProps extends StateProps, DispatchProps, RouteComponentProps<{ url: string }> {}
export const InvoiceItem = (props: IInvoiceItemProps) => {
const { invoiceItemList, match, loading } = props;
return (
<div>
<h2 id="invoice-item-heading">
Invoice Items
</h2>
</div>
) 
}
const mapStateToProps = ({ invoiceItem }: IRootState) => ({
invoiceItemList: invoiceItem.entities,
loading: invoiceItem.loading,
totalItems: invoiceItem.totalItems,
links: invoiceItem.links,
entity: invoiceItem.entity,
updateSuccess: invoiceItem.updateSuccess,
});
const mapDispatchToProps = {
getEntities,
reset,
};
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;
export default connect(mapStateToProps, mapDispatchToProps)(InvoiceItem);

这里,我想从InvoiceDetails传递一些数据到InvoiceItems。我如何传递它并在InvoiceDetails中访问它?

作为一个例子,我想在IvoiceItems中传递InvoiceDetails ID(主键)来获取相应的数据。

在React中,将数据从子节点传递给父节点很简单。在父组件中创建一个状态变量:

const [data, setData] = useState({});
然后,在您的JSX中,传递setData函数:
<InvoiceDetails {...props} setData = {setData} />

然后在你的InvoiceDetails组件中,你可以调用setData并将其设置为你想要的任何值,这也将更新父组件中的状态变量。

相关内容

  • 没有找到相关文章