首页 > 解决方案 > 想要在 Reactjs 中的数组中并作为道具传递的字符串中提供超链接

问题描述

我正在从一个数组中提供静态文本数据,该数组在我的 React 组件中进一步“映射”

const LinkElement = () => <Link to='/some-redirection-in-the-same-app'>Click here...</Link>

const EyelashGrowthData = [
    {
        key:"How does bimatoprost 0.03% ophthalmic solution work?",
        data:`It is believed the growth cycle (anagen) phase is increased of your eyelash hair cycle. Anagen is the
        growth phase of all hair. The increase in the length of the anagen phase therefore increases the
        number of hairs in this growth phase.`   
    },
    {
        key:"Is a doctor’s consultation and prescription required for this treatment?",
        data:`Yes, this is a prescription-only medication to grow the eyelashes longer, fuller and darker, indicated
        for people with inadequate or not enough lashes. This treatment needs to be prescribed by a doctor
        to assure the proper treatment and use. Complete the ${LinkElement} now.`   
    }
];

EyelashGrowthData将进一步传递给 prop 中的某个组件,并成为data下面组件的 prop 并像这样提供服务。可能有很多变体data可能没有超链接,但其中一些具有应该存在的超链接。

EyelashGrowthData在传递给下面的组件之前有许多级别的组件

export ({data}) => {
   data.map(item => { 
       return (
            <>
            <Typo>
                {item.key}
            </Typo>
            <Typo>
                {item.data}
       //this should render a ${LinkElement} in {item.data}, which will work perfectly as a link
            </Typo>
            ......many other thing
            </>
       )
   })
}

标签: reactjsreact-router-dom

解决方案


一种方法是将数据键更改为返回 JSX 的 React 函数:

const LinkElement = () => <Link to='/some-redirection-in-the-same-app'>Click here...</Link>

const EyelashGrowthData = [
    {
        key:"How does bimatoprost 0.03% ophthalmic solution work?",
        data: () => `It is believed the growth cycle (anagen) phase is increased of your eyelash hair cycle. Anagen is the
        growth phase of all hair. The increase in the length of the anagen phase therefore increases the
        number of hairs in this growth phase.`   
    },
    {
        key:"Is a doctor’s consultation and prescription required for this treatment?",
        data: () => <> Yes, this is a prescription-only medication to grow the eyelashes longer, fuller and darker, indicated
        for people with inadequate or not enough lashes. This treatment needs to be prescribed by a doctor
        to assure the proper treatment and use. Complete the <LinkElement/> now.</>  
    }
];

然后你可以从你的第二个组件中简单地调用数据函数。您还可以处理字符串以及诸如{typeof item.data === 'function' ? item.data() : item.data }.


推荐阅读