[英]Passing an object from one component to another using props
I am trying to pass a whole object from one component to another on button click. 我试图在单击按钮时将整个对象从一个组件传递到另一个组件。
I have tried using Link and Router, but I still cannot see the object inside the props of the destination component. 我尝试使用链接和路由器,但仍然看不到目标组件的道具内的对象。
I am using the onClick handler handleReportIncident to pass an available object while Routing to this component. 我正在使用onClick处理程序handleReportIncident在路由到此组件时传递可用对象。 The handleReportIncident function is bound at the top.
handleReportIncident函数绑定在顶部。
handleReportIncident() {
const { trip } = this.state;
this.props.history.push(`/app/new`)
return (
<div>
<New trip={trip} />
</div>
)
}
render() {
return (
<Button
variant="contained"
color="primary"
className={classes.toolbarButton}
onClick={this.handleReportIncident}
>
<AddIcon />
Incident
</ Button>
)}
Inside of New component I have : 在新组件内部,我有:
class New extends Component {
render() {
const {trip} = this.props;
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
trip: PropTypes.object.isRequired,
};
Note: I am using material UI as a theme. 注意:我正在使用实质性UI作为主题。
The Log inside the New component is the trip is undefined
. New组件内部的Log是行程
undefined
。
You can wrap your desired object in the state of the Link. 您可以将所需的对象包装在链接状态。 See example below.
请参见下面的示例。
// Main Component from which you want object passed //要从中传递对象的主要组件
render() {
return (
<Link to = {{
pathname: '/app/new',
state: {
trip: this.state.trip
}
}}>
<AddIcon /> Incident
</Link>
)
}
// New Component get desired object from this.props.location.state
//新组件从
this.props.location.state
获取所需的对象
class New extends Component {
render() {
const { trip } = this.props.location.state
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
trip: PropTypes.object.isRequired,
}
For more info on how it works head over to this tutorial: https://tylermcginnis.com/react-router-pass-props-to-link/ 有关其工作原理的更多信息,请转到本教程: https : //tylermcginnis.com/react-router-pass-props-to-link/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.