如何使用onClick事件将一些数据传递到新Route中,从而重定向到React中的其他Route?
onDayClick = (e, day) => {
this.setState({
selectedDay: day
}, () => {
console.log("SELECTED DAY: ", this.state.selectedDay);
});
if (day.toString().length === 1) {
day = "0" + day;
}
let dateClickedOn = this.month() + " " + day + ", " + this.year();
this.props.onDayClick && this.props.onDayClick(e, day, this.state.today.format("MMMM DD, YYYY"), dateClickedOn);
// Redirect here with dateClickedOn variable passed to new route
}
答案 0 :(得分:2)
假设您使用的是React Router 4.x react-router-dom
,则可以将BrowserRouter与更高级别的withRouter组件一起使用,以显示可用于编程的道具history通过方法push(path, [state])
浏览。
基础:
import { BrowserRouter as Router } from "react-router-dom";
<Router>
// your awesome app
</Router>
组件:
import { withRouter } from "react-router-dom";
// ...
onDayClick = (e, day) => {
this.setState({
selectedDay: day
}, () => {
console.log("SELECTED DAY: ", this.state.selectedDay);
});
if (day.toString().length === 1) {
day = "0" + day;
}
let dateClickedOn = this.month() + " " + day + ", " + this.year();
this.props.onDayClick && this.props.onDayClick(e, day, this.state.today.format("MMMM DD, YYYY"), dateClickedOn);
// use history.push() method to redirect
this.props.history.push('/some-route', { dateClickedOn });
}
// ...
export default withRouter(SomeComponent);
在接收组件中,您应该能够从props.location.state
访问此传递状态,例如:
import { withRouter } from 'react-router-dom';
// ...
render() {
const { dateClickedOn } = this.props.location.state;
}
// ...
export default withRouter(SomeOtherComponent);
希望有帮助!
答案 1 :(得分:0)
为此,您首先需要修改<Router>
组件并添加一个history
属性:
import createHistory from "history/createBrowserHistory";
export const history = createHistory();
...
<Router history={history}>
...
</Router>
此后,您需要将创建的同一history
对象导入要导航的位置,因此,在您的情况下:
onDayClick = (e, day) => {
this.setState({
selectedDay: day
}, () => {
console.log("SELECTED DAY: ", this.state.selectedDay);
});
if (day.toString().length === 1) {
day = "0" + day;
}
let dateClickedOn = this.month() + " " + day + ", " + this.year();
this.props.onDayClick && this.props.onDayClick(e, day, this.state.today.format("MMMM DD, YYYY"), dateClickedOn);
history.push(/* your route */, { date: dateClickedOn });
}
如果您需要更多信息,可以在这里阅读:https://github.com/ReactTraining/history