繁体   English   中英

使用道具将对象从一个组件传递到另一个组件

[英]Passing an object from one component to another using props

我试图在单击按钮时将整个对象从一个组件传递到另一个组件。

我尝试使用链接和路由器,但仍然看不到目标组件的道具内的对象。

我正在使用onClick处理程序handleReportIncident在路由到此组件时传递可用对象。 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>
)}

在新组件内部,我有:

class New extends Component {
render() {
const {trip} = this.props;
console.log("the trip is", trip);
return(
...
)
}
New.propTypes = {
    trip: PropTypes.object.isRequired,
};

注意:我正在使用实质性UI作为主题。

New组件内部的Log是行程undefined

您可以将所需的对象包装在链接状态。 请参见下面的示例。

//要从中传递对象的主要组件

render() {

  return (
    <Link to = {{
      pathname: '/app/new',
      state: {
        trip: this.state.trip
      }
    }}>
      <AddIcon /> Incident 
    </Link>
  )
}

//新组件从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,
}

有关其工作原理的更多信息,请转到本教程: https : //tylermcginnis.com/react-router-pass-props-to-link/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM