我有两个组件Car和CarDetails 我想在汽车组件中显示所有汽车,并带有超链接/链接,当用户点击它时,应将carid(param(s))传递给CarDetails组件
App.js
import React, { Component } from 'react';
import Cars from './components/Cars';
import CarDetails from './components/Car-details'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
class App extends Component {
render() {
const data = [
{
id: 1,
name: 'Honda Accord Crosstour',
year: '2017',
model: 'Accord Crosstour',
make: 'Honda'
},
{
id: 2,
name: 'Mercedes-Benz AMG GT Coupe',
year: '2016',
model: 'AMG',
make: 'Mercedes Benz'
}
];
return (
<div className="App">
<hr/>
<Cars varCars={data}/>
</div>
);
}
}
export default App;
Cars.js 此组件显示所有带有超链接的汽车,当点击时将调用 carnama.js显示该特定车辆的详细信息
import React, { Component } from 'react';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import Carnama from './Carnama'
class Cars extends Component {
constructor(props) {
super(props)
}
render(){
const cars = this.props.varCars;
const carNode = cars.map((car) => {
return (
<Router>
<div>
<Link
to={{ pathname: '/Carnama/'+car.id}}
className="list-group-item"
key={car.id}>
{car.name}
</Link>
<Route path="/Carnama:id" component={Carnama}/>
</div>
</Router>
)
});
return (
<div>
<h1>Cars page</h1>
<div className="list-group">
{carNode}
</div>
</div>
);
}
}
export default Cars;
Carnama.js 此组件显示传递的参数car.id
import React, { Component } from 'react';
class Carnama extends Component {
render() {
return (
<div>
<h1>Car Details</h1>
</div>
);
}
}
export default Carnama;
我已阅读并重新阅读以下内容 https://reacttraining.com/react-router/web/example/url-params https://jaketrent.com/post/access-route-params-react-router-v4/
答案 0 :(得分:0)
您的问题在于此块:
const carNode = cars.map((car) => {
return (
<Router>
<div>
<Link
to={{ pathname: '/Carnama/'+car.id}}
className="list-group-item"
key={car.id}>
{car.name}
</Link>
<Route path="/Carnama:id" component={Carnama}/>
</div>
</Router>
)
});
Array.map将返回一个新的React组件数组,每个组件都包含在<Router>
组件中。我还没有测试过,所以我不确定它是否会起作用,但尝试类似下面的内容:
const carNode = cars.map((car, i) => {
return (
<div key={i}>
<Link
to={{ pathname: '/Carnama/'+car.id}}
className="list-group-item"
key={car.id}>
{car.name}
</Link>
</div>
)
});
return (
<div>
<h1>Cars page</h1>
<div className="list-group">
<Router>
{carNode}
<Route path="/Carnama:id" component={Carnama}/>
</Router>
</div>
</div>
);