简体   繁体   中英

How to pass a value to a child component in react

I have two components, one which calls the other. In this case my component Entries has the below line.

<TypeIcon typeicon={entry.type} />

This line calls the below component TypeIcon .

import React from 'react';

import '../../App.css'




function TypeIcon (props){

  return (
    <span><i class="fa fa-file-text" aria-hidden="true"></i></span>
  )
}

export default TypeIcon

What I'm attempting to do is to do some conditional rendering on the type value (show a doc icon or a play icon) which is switched on the value in entry . The JSON below is mapped to entry :

[{
    "domain": "https://matangitonga.to",
    "publishdate": "2017-09-06",
    "title": "Tonga's general election set for November 16",
    "type": "article",
    "language": "EN",
    "event_id": 1,
    "id": 1,
    "url": "https://matangitonga.to/2017/09/06/tongas-general-election-set-november-16"
}]

What I'm having trouble with is the way in which to correctly pass either entry or entry.type into TypeIcon .

if you pass the value as

<TypeIcon typeicon={entry.type} />

then you can access it in children component as

{props.typeicon}

because all your props are passed through the props object and typeicon is just a key in your props object

if you pass the whole entry object then you can access the icon in your child compoent as.

{props.typeicon.type}

because the whole entry object become the value for the key typeicon and to access the type property you have to access it one step deeper

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