我是React的新手,因此任何帮助将不胜感激!将对象从一个组件传递到另一个组件In React
UserPage.js:
import React, { Component } from 'react';
import { Link } from 'react-router';
import request from 'superagent';
export default class UserPage extends Component {
constructor(props) {
super(props);
this.state = {
listSchool: []
};
}
componentWillMount() {
let self = this;
request
.get('/api/schools/')
.set('Accept', 'application/json')
.end(function (err, res) {
self.setState({ 'listSchool': res.body });
console.log(self);
});
}
render() {
let marginLeft = {
marginLeft: "10px"
};
return (
<div className="container">
<form className="form-inline">
<div className="form-group">
Xin chào: <label style={marginLeft}>{this.props.location.state.name} </label>
<div className="btn-group" style={marginLeft}>
<button type="button" className="btn btn-info">Choose Your School</button>
<button type="button" className="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span className="caret"></span>
<span className="sr-only">Toggle Dropdown</span>
</button>
<ul className="dropdown-menu">
{
this.state.listSchool.map(school => {
return (
<li key={school._id}>
<Link to={`schools/${school._id}`}
params={
{
user : {
id : this.props.location.state.id,
name : this.props.location.state.name,
},
school : {
id : school._id,
name : school.TenTruong
}
}
}>
{school.TenTruong}
</Link>
</li>
);
})
}
</ul>
</div>
</div>
</form>
</div>
);
}
}
SchoolPage.js:
import React, { Component } from 'react';
export default class SchoolPage extends Component {
constructor(props) {
super(props);
this.state = {
user : {},
school : {},
};
}
componentWillMount() {
console.log(this.props);
}
render() {
return (
<div>
Hello {this.props.params.id}
</div>
);
}
}
routes.js:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Layout from './components/Layout';
import IndexPage from './components/IndexPage';
import UserPage from './components/UserPage';
import SchoolPage from './components/SchoolPage';
const routes = (
<Route path="/" component={Layout}>
<IndexRoute component={IndexPage}></IndexRoute>
<Route path="users/:id" component={UserPage}></Route>
<Route path="schools/:id" component={SchoolPage}></Route>
</Route>
);
export default routes;
如何传递的对象从链接标签从UserPage的Component SchoolPage组件并使用它。
我已经搜索并知道这是不可能通过链接标记传递一个对象,所以在React我怎么能通过它。 Tks为您提供帮助!
我的意思是如何将1个对象从UserPage组件传递给SchoolPage组件 –
@ M.Tae我认为从Link中是不可能的。你可以通过应用商店的id来获得一些对象。你可以在你的SchoolPage组件上为它写一个容器。 – viktarpunko