【问题标题】:Add dynamic link from a object in React从 React 中的对象添加动态链接
【发布时间】:2023-01-25 00:29:24
【问题描述】:

我是 React 的新手,我正在尝试在 React 组件中插入一个链接。我做了一个对象,每个项目都包含一个外部链接。这个对象:

export const myList =
[
    {
        "id":"P1",
        "title":"Title1",
        "description":"The first description",
        "link":"https://random-link.io",
        "cover":require("../img/myImg1.webp")
    },
 
    {
        "id":"P2",
        "title":"Title2",
        "description":"The second description",
        "link":"https://random-link2.io",
        "cover":require("../img/my2ndImg.webp")
    },

... 

主要思想是为列表的每个项目创建页面,并链接到外部页面以“查看更多信息”。

我试着这样做:

function Page() {
   
    const id = useParams();
    const pageList = myList.find(list => list.id === id.id);


    return(
        <>
            {
                pageList ? (
                    <div className="Page">
                        <img className="ListCover" src={pageList?.cover} alt={pageList?.title}/>
                      
                            <div className="information-list">
                                <span className="title-list">{pageList?.title}</span>
                              
                                                   
                        </div>
                        <div className="description-list">
                            <Dropdown titre="Description" description={pageList?.description} link={pageList?.link} />
                           
                        </div>
                    </div>
                ) : <Navigate replace to="/404"/>
            }
        </>
    )
}

export default Page;

在下拉组件中,我做了这个:

function Dropdown({title, description, link}) {
    
    const [open, setOpen] = useState(false);

    return(
        <div className="dropdown" id={`dropdown-${title}`}>
            <div className="header-dropdown">
                <div className="title-dropdown">{title}</div>
                <span className={`arrow-dropdown ${open}`} onClick={() => setOpen(!open)}>
                    <img src={arrow} alt="Open it"/>
                </span>
            </div>
            {
                /* if dropdown is TRUE then it show the description */
                open && <div className="description-dropdown">{description}
                <a href={{pathname:{link}}} rel="noreferrer"> See more</a> </div>
            }
        </div>
    );
}

export default Dropdown;```

The problem is that the link send me to : http://localhost:3000/[object%20Object]; with another method I got http://localhost:3000/myProjet/https://random-link.io 

Thanks 

【问题讨论】:

    标签: reactjs object hyperlink


    【解决方案1】:

    我相信你的代码中唯一的问题是你试图使用一个对象作为 href 的参数,它需要一个字符串,试着把链接放在那里,它应该可以工作。它应该看起来像:

    <a href={link} rel='noreferrer'>
    

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 2021-06-20
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 2011-08-26
      相关资源
      最近更新 更多