我在名為“ProductCard”的組件中生成了一個帶有“navlink”的鏈接,我想將道具傳遞給名為“Product”的組件
產品卡組件
import React, {Component} from "react";
import {NavLink} from "react-router-dom";
class ProductCard extends Component{
render() {
return (
<div className="col-xl-4 col-md-6 col-xs-12">
Name : {this.props.product.name}<br/>
Price : {this.props.product.price}<br/>
<NavLink
to={{
pathname:"/product/" `${this.props.producto.id}`,
aboutProps:{
product_id: `${this.props.product.id}`,
product_name: `${this.props.product.name}`,
product_sku: `${this.props.product.sku}`,
}
}}
exact
> Show product
</NavLink>
</div>
);
}
}
export default ProductCard;
Product.js 組件
import React, {Component} from "react";
class Product extends Component{
constructor(props) {
super(props);
console.log(props.location.aboutProps);
this.state = {
products: []
}
}
render() {
return (
<div className="app container" style={{backgroundColor: "red", padding: "10px"}}>
Product<br/>
</div>
);
}
}
export default Product;
正如我所說,我遇到的問題是能夠將父 ProductCard 組件的屬性傳遞給子產品組件
uj5u.com熱心網友回復:
編輯:改為使用狀態
state: {
product_id: this.props.product.id,
product_name: this.props.product.name,
product_sku: this.props.product.sku
}
像這樣訪問道具: props.location.state.product_id
uj5u.com熱心網友回復:
TLDR:改變你的方法。帶指標的例子
此處示例 https://codesandbox.io/s/brave-visvesvaraya-81c0p?file=/src/App.js
除了@ilernet 的回答,我想就你的代碼給出一些提示:
使用上面的解決方案,您的鏈接最終會像
/products/1/test/1223345. 如果您有大量資料,這不是一個好習慣
const linkData = await fetch(`/productdata`);
// linkData will equal array of 10 products
// { id: 1, sku: 1, name: "Product 1"}
linkData.forEach(data => {
return (
<NavLink
to={{
pathname:"/product/" `${data.id}`,
aboutProps:{
product_id: `${data.id}`,
product_name: `${data.name}`,
product_sku: `${data.sku}`,
}
}}
exact
>
Show product
</NavLink>
);
}
但
使用 React,您應該根據每個組件的需要加載盡可能多的資料。
建議
- 改變你的鏈接方法
// This accepts anything like /product/123
<Route
exact
path="/product/:id"
render={({ match }) => {
// Render can be used to instead of state - to inject props directly into a component
return <ProductCard id={Number(match.params.id)} />;
}}
/>
- 在 Product/ProductCard 組件中獲取您的資料
import React, { Component } from "react";
class ProductCard extends Component {
constructor(props) {
super(props);
// Replaces a fetch()/API request
this.state = {
products: [
{
id: 123,
name: "Test",
price: 1234
}
]
};
}
render() {
const { name, price } = this.currentProduct;
return (
<div className="col-xl-4 col-md-6 col-xs-12">
Name : {name}
<br />
Price : {price}
<br />
</div>
);
}
get currentProduct() {
const { id } = this.props;
if (!id) {
return {
name: "No Item",
price: 0
};
}
const { products } = this.state;
const currentProduct = products.find((product) => product.id === id);
return {
name: (currentProduct && currentProduct.name) || "No Item",
price: (currentProduct && currentProduct.price) || 0
};
}
}
export default ProductCard;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/343125.html
