简体   繁体   English

传入 object 作为道具反应

[英]Pass in object as prop react

I have a function class:我有一个 function class:

function TopicBox({topicName, article1}) {
    return (
        <div className="TopicBox">
            <h1>{topicName}</h1>
            <div className="topicDivider" />
            <Article 
                    articleImageLink={article1.imageLink} />

--MORE CODE--
export default TopicBox

As you can see it takes in the props topicName, which is just a string, and article1 which is an object.正如你所看到的,它接受了props topicName,它只是一个字符串,以及article1,它是一个object。 article1 variable will have child components, such as.imageLink as seen on the last line of code. article1 变量将具有子组件,例如在最后一行代码中看到的 .imageLink。 Now on another file called I want to create a topic box like such:现在在另一个名为我想创建一个主题框的文件上,如下所示:

<TopicBox topicName="Hi" 
                        article1={imageLink:"google.com",
                                title:"hi"}/>

So again the topicName prop is just a string, so that works fine.所以 topicName 道具只是一个字符串,所以它工作正常。 Now I'm creating a new object called article1 that contains the child variable imageLink.现在我正在创建一个名为 article1 的新 object,其中包含子变量 imageLink。 However this code doesn't work.但是,此代码不起作用。 I get the following error:我收到以下错误:

Parsing error: Unexpected token, expected "}"

  10 |             <div className="TopicLists">
  11 |                 <TopicBox topicName="Hi" 
> 12 |                         article1={imageLink:"google.com",
     |                                            ^
  13 |                                 title:"hi"}/>
  14 |                 <TopicBox />

So to debug, I tried replacing the: to a = when I create the child object, but I get another error:所以为了调试,当我创建子 object 时,我尝试将:替换为 a =,但我得到另一个错误:

'imageLink' is not defined.eslintno-undef

Can you please let me know how to pass in an object as a prop?你能告诉我如何传递一个 object 作为道具吗?

Thanks!谢谢!

Try this way试试这个方法

<TopicBox
  topicName="Hi"
  article1={{ imageLink: "google.com", title: "hi" }}
></TopicBox>

You can do it like this;你可以这样做;

const article1 = {imageLink: "google.com", title: "hi"}
<TopicBox
  topicName = "Hi"
  article1 = {article1} />

Another way you can do this is by passing an object property as individual props using spread operator;另一种方法是使用扩展运算符将 object 属性作为单独的道具传递;

const article1 = {imageLink: "google.com", title: "hi"}
<TopicName 
  topicName = "Hi"
  {...article1} />

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

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