简体   繁体   中英

How to pass data from one component to another via a function in ReactJS?

How can I pass the data parameter from the openTeam function to another component in another file? The data can't change value, because it has an id in it that can't be changed. I am using functional components in my app.

const openTeam = (data) => {
        history.push("/" + data.name)
        return (
            <div>

            </div>
        )
    }

    return (
        <div>
            <Welcome />
            <div>
                <ul>
                    {teams.map((data) => {
                        return (
                            <li onClick={() => openTeam(data)} key={data.teamId}>
                                <h1>{data.name}</h1>
                                <p>{data.teamId}</p>
                            </li>
                        )
                        })}
                </ul>
            </div>
        </div>
    )
}

You can pass data like this to navigated component

const openTeam = (data) => {
    this.props.history.push({
      pathname: '/',
      state: { passedData: data }
    })
}

and access like this

this.props.location.state.passedData

Or or similarly for the Link component

<Link to={{
   pathname: '/',
   state: {passedData: data}
 }}> {data.name} </Link>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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