反应shopify结账扩展,动态添加链接到文本中

问题描述 投票:0回答:1

我正在开发 Shopify 扩展 React 组件,并希望从设置(shopify 功能)动态添加文本。我的主要目标是在文本中找到 {link_placeholder} 字符串并将其更改为真实文本。 我的组件看起来像这样

function Extension() {

const {static_content_text} = useSettings();

const link = "https://test.com";
const link_text = "some link text";

const replacedText = static_content_text.replace(
    /\{LINK_PLACEHOLDER\}/g,
    `<Link appearance="base" to="${link}">${link_text}</Link>`
);

return (
  <BlockStack>
      <Text>
          {replacedText}
      </Text>
  </BlockStack>
  );
}

问题是链接标签作为纯文本插入,而不是呈现为实际链接,

如何解决?预先感谢

javascript reactjs shopify
1个回答
0
投票

React 将对渲染的纯字符串进行转义,但是您可以渲染 React 内容的数组。因此,不要将链接添加为文本,而是创建一个包含字符串开头、链接组件、字符串结尾的数组。

一个非 React 示例(因为它使代码片段更加简单):

const static_content_text = 'Example text with a {LINK_PLACEHOLDER} in the middle'

const textArray = static_content_text
  .split(/\{LINK_PLACEHOLDER\}/g)
  .flatMap((text) => ([
    text, 
    // Replace this string with your component
    // <Link appearance="base" to={link}>{link_text}</Link>
    'Add your link component here instead of this string'
   ]))
  .slice(0, -1)
 
// This is just for the example
console.log(textArray)

/* Then in the render method:
return (
  <BlockStack>
      <Text>
          {textArray}
      </Text>
  </BlockStack>
  )
}
*/

© www.soinside.com 2019 - 2024. All rights reserved.