簡體   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