简体   繁体   中英

React, how to dynamically create components inside a string?

I know how to dynamically create react components based on lists, as the docs indicate. However, I want to create them dynamically but not together, with some strings in between. Specifically, I want to contain every regex in some custom components.

For example:

The cat is playing with the dog and the mouse

becomes

The <animal>cat</animal> is playing with the <animal>dog</animal> and the <animal>mouse</animal>

I know how to do the regex, but just adding the tags to the string would have them be still strings, instead of components.

Return an array of strings and React components

import React from "react";

export default function App() {
  return (
    <div>
      {"The cat is playing with the dog and the mouse"
        .split(/(cat|dog|mouse)/)
        .map((x, i) => (i % 2 ? <Animal>{x}</Animal> : x))}
    </div>
  );
}

function Animal({ children }) {
  return <span style={{ color: "red" }}>{children}</span>;
}

https://codesandbox.io/s/nice-browser-950gx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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