简体   繁体   中英

How to reference JSX component props from array?

I have JSX components in an array, and want to reference their props and state by accessing them in the array.

let default = [
    <Space name="1" />,
    <Space name="2" color="#ffffff" />
]

let selected = default[0];  

This gives me the error Cannot read property 'name' of undefined when trying to access the name prop I have set by doing selected.name .

I also tried using an array of regular objects ( [new Space('1', '#ffffff'), etc] ) and rendering them with a map, but while this let me access props from the array directly, I couldn't access the props from the render method.

I'm new to react so any help is appreciated.

The right way to do this are: Separate this two things. Declare an Array of objects likes this: const default = [{name: "Godzilla Firefox"}, {name: "Metallica"}] or not objects: const default = ["Samsung", "Apple"] . Then, you can make a map in the Array. const data = default.map(value ⇒ <Space key={value} name={value} />) . Like this you can easily access the values. So, put in your render method the {data} . It's will be re-render every time as you change.

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