[英]How to transfer data between pages in Reactjs
我正在嘗試將數據從DropDownItem
組件傳輸回我的類組件,而我無法使用props做到這一點。 在此示例中,我想將單擊項的props.product
傳輸到我的應用程序組件。 誰能告訴我最好的方法是什么? 提前致謝。
當我單擊一個下拉選項時,我想將其顯示為我的主類組件中的一個實例。 我已經嘗試為此目的創建一個特殊的組件,但是它使代碼變得非常復雜。
class App extends Component {
constructor(props) {
super(props)
this.state = {
products: []
}
}
async fetchDevices() {
const url = 'my url';
const response = await fetch(url, { method: 'GET', headers: headers });
const data = await response.json()
this.setState({ products: data.value })
}
componentDidMount() {
this.fetchDevices();
}
render() {
const productItems = this.state.products.map((productValue, index) => {
return (<DropDownItem key={index} product={productValue.name} />)
})
return (
<div>
{this.state.products[0] && Array.isArray(this.state.products) ?
<div>
<DropdownComponent
isOpen={this.state.dropdownOpen}
toggle={this.toggle}
product={productItems}
/>
</div> :
<div>loading...</div>}
<p></p>
</div>
)
}
}
export default App
function DropDownItem(props) {
return (
<div>
<DropdownItem onClick={() => console.log("selected product", props.product)}>
{props.product}</DropdownItem>
<DropdownItem divider />
</div>
)
}
export default DropDownItem
我想在我的App組件中顯示所選項目
組件之間的數據傳輸的一般規則是:
App
)轉移到子組件( DropDownItem
),請使用props
示例(未經測試,僅用於展示想法)
// App component
...
selectDropDownItem(item) {
this.setState({selectedItem: item});
}
render () {
return
// ...
<DropdownComponent
isOpen={this.state.dropdownOpen}
toggle={this.toggle}
product={productItems}
selectItemCallback={this.selectDropDownItem.bind(this)}/>
//...
// DropDownItem component
function DropDownItem (props) {
return (
<div>
// bind to props.product so when called props.product will be passed as argument
<DropdownItem onClick={props.selectItemCallback.bind (null, props.product)}>
{props.product}</DropdownItem>
<DropdownItem divider/>
</div>
)
}
export default DropDownItem
一般的想法是您將回調從父級傳遞到子級。 當孩子需要與父母溝通時,它只調用在props中傳遞的回調,並將所需的數據作為該回調的參數傳遞(在您的示例中,可以選擇此項)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.