如何在 React 中将数据从一个组件传递到另一个组件?
props用于在组件之间传递数据。我们通常使用它来将数据从父组件传递到子组件。
但是,如果需要从子组件向父组件传递数据怎么办?如果需要在同级组件之间传递数据怎么办?
可以将数据从一个组件传递到另一个组件的方式有很多种:
1. 使用道具
您可以使用props它将数据从父组件传递到子组件。Example 1以下示例代码展示了如何实现此功能。
|--- App.js
|---- ParentComponent
|----ChildComponent
2. 使用React ContextAPI或状态管理库,例如Redux
Redux或React ContextAPI提供了集中式状态管理功能,用于管理您的应用程序。这意味着所有应用程序状态都将存储在一个名为Store 的单一位置。
就像传统数据库代表应用程序的记录点一样,您的Store可以被视为客户端的“单一数据源”或数据库。
示例 1 — 使用 Props 将数据从父组件传递到子组件
ParentComponent.js
import React from 'react'
import ChildComponent from './ChildComponent';
class ParentComponent extends React.Component {
render(){
return(
<div>
<ChildComponent message="Data from first component"/>
</div>
);
}
}
export default ParentComponent;
ChildComponent.js
import React from 'react';
const ChildComponent = (props) => {
return(
<h2> {props.message} </h2>
);
}
export default ChildComponent;
以上代码片段展示了如何将数据从父组件传递到子组件。
但是,如果我们需要将数据从子组件传递到父组件该怎么办呢?接下来我们来看看!
3. 使用 Props 作为回调函数
如果你没有使用任何状态管理库(例如 ` Reduxor` 或 `)React ContextAPI,并且需要将数据从子组件传递到父组件,那么回调函数就派上用场了。
---App
|---- Table.js
|---- ListItem.js
预览
使用场景- 当点击表格中的任何行时,实现从表格中获取该行数据并在表格主页上显示的功能。
解决方案——使用 Props 作为回调函数。让我们通过下面的示例来了解一下!
import React from 'react'
import ListItem from './ListItem';
export class Table extends React.Component {
// Dummy data for the table
state = {
data: tableData
}
getData = (rowData) => {
// This is the row data from ChildComponent
console.log(rowData);
}
render(){
return(
<div>
{this.state.data.map(item => (
<ListItem rowData={item} handleClick={this.getData}/>
))}
</div>
);
}
}
import React from 'react';
const ListItem = (props) => {
return(
// Using Props handleClick as callback function
<div onClick={()=> props.handleClick(props.rowData)}>
<p> {props.rowData.company} </p>
<p> {props.rowData.contact} </p>
<p> {props.rowData.country} </p>
</div>
);
}
export default ListItem;
希望你现在已经理解了 React 组件之间的数据传递机制。如果你发现任何错误,请在下方留言指正。我仍在学习并记录我的学习成果。
我很想知道您对这篇文章的看法和评价。
干杯!
文章来源:https://dev.to/dipakkr/how-to-pass-data-from-one-component-to-other-component-in-react-35i2

