使用占位符从字符串构建React组件

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

我需要基于结构一致的文本以未知顺序动态构建React组件。如何用相应的组件替换占位符编号(以某种一致的方式标识,请参见下文)?

const text = "some (1) arbitrary amount of [2] text";

return (
  <div>
    some
    <Component1 />
    arbitrary amount of 
    <Component2 />
    text
   </div>
)

[]和()的位置和顺序不一致,所以:

const text = "[2] some arbitrary amount (1) of text";

return (
  <div>
    <Component2 />
    some arbitrary amount
    <Component1 />
    of text
   </div>
)
reactjs dynamic react-component
1个回答
0
投票

有点棘手,为简单起见,我们仅替换一个占位符(1)

const App = () => {
  return <div>{splitAndRender(text, `(1)`, Component1)}</div>;
};

splitAndRender的实现方式如下:

const splitAndRender = (text, regex, Component) => {
  const splitByRegex = text.split(regex);
  return splitByRegex.reduce((acc, curr, index) => {
    const isLastItem = index === splitByRegex.length - 1;
    return [...acc, curr, isLastItem ? null : <Component key={index} />];
  }, []);
};

对于未知数量的占位符,应通过从splitAndRender恢复返回的数组,查找字符串,并在此类字符串上调用splitAndRender来完成。

Edit mystifying-thompson-j9e2m

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