gpt4 book ai didi

javascript - React router 如何在现有组件内渲染新组件

转载 作者:行者123 更新时间:2023-11-28 04:36:41 25 4
gpt4 key购买 nike

这很难解释,但假设我顶部有一个导航栏,其中包含所有主要链接。我单击顶部导航栏中的模型链接,它会在下面呈现模型页面。模型页面包含不同模型的缩略图。我怎样才能获得它,以便单击该模型的缩略图可以加载该人的组件来代替模型页面?

这是我到目前为止所拥有的。顺便说一句,我正在使用 React-router 3.0.5

App.jsx:

import React from 'react';
import LeftPane from './LeftPane.jsx';
import RightPane from './RightPane.jsx';
import CenterPane from './CenterPane.jsx';
import TopPane from './TopPane.jsx';
import Models from './Models.jsx';
import Projects from './Projects.jsx';
import Contact from './Contact.jsx';
import Router from 'react-router';
import axios from 'axios';

class App extends React.Component {
constructor() {
super();
this.state = { modelBucket: [] };
}

componentWillMount() {
axios({
method: 'POST',
url: '/modelcall'
})
.then((response) => {
console.log('this is the axios call from models.jsx (the response) :', response);
this.setState({modelBucket: response});
})
.catch((error) => {
console.log('this is an error from the axios call in models.jsx', error);
});
}

render() {
return (
<div>
<div className="container-fluid">
<div>
<TopPane />
</div>

<div className="container-fluid">
<div className="row content imageThumbMargin">
<div>
{React.Children.map(this.props.children, child => React.cloneElement(child,
{
modelNames: this.state.modelBucket.data,
path: this.props.route.path
})
)}
</div>
</div>
</div>
</div>
</div>
);
}
}

export default App;

Model.jsx:(模型卡是单独的缩略图)

import React from 'react';
import ModelCard from './ModelCard.jsx';
import axios from 'axios';

class Models extends React.Component {
constructor() {
super();
this.state = { modelList: [] };
}

render() {
return (
<div>
<p className = "text-center">Models Page</p>
{this.props.modelNames.map((model, i) => {
return (
<div key={i} className = "imageThumbs col-md-2">
<ModelCard key={i} model={model} />
</div>
);
})}
</div>
);
}
}

export default Models;

和 ModelCard.jsx:

import React from 'react';
import {Link} from 'react-router';

class ModelCard extends React.Component {
constructor(props) {
super(props);
}


render () {
return (
<div>
<Link to={'/' + this.props.model.name}><div>
<img src={this.props.model.imageUrl} />
<p className="text-center imageMarginRight">{this.props.model.name}</p>
</div></Link>
</div>
);
}
}

export default ModelCard = ModelCard;

最佳答案

将导航栏保持在其他组件“之上”的一种方法是渲染基本路由,然后将其他路由嵌套在其中:

<Route path='/'>
<Route path='/modelcards' component={ModelCards} />
<Route path='/modelcards/:id' component={Model} />
<Route>

然后您可以调用 browserHistory.push('/modelcards/${id}') 并且参数 id 将在 this.props.params.id 下可用您可以在 render 函数中渲染适当的卡片。如果你想传递很多参数并且不一定要为其创建路由,你可以在推送调用中传递参数: browserHistory.push({ pathname:'/modelcards', params: { id :...,标题:... })

关于javascript - React router 如何在现有组件内渲染新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44148463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com