Is it possible to change a substring within a string to a different HTML tag or attribute?
P粉852114752
P粉852114752 2023-09-13 16:34:08
0
1
454

There is a React component that accepts a string as a property:

interface MyProps {
  myInput: string;
}

export function MyComponent({ myInput }: MyProps) {
   ...
   return (
     <div>
       {myInput}
     </div>
   );
};

This component is used elsewhere:

<MyComponent myInput="请通过test@test.com与我们联系" />

My question is, can we change the color of the email address in this case? For example, change it to blue.

Or better yet, wrap that text in:

<a href="mailto:test@test.com" target="_blank">
   test@test.com
</a>

Not sure if something like this is possible if the type of the property is string.

P粉852114752
P粉852114752

reply all(1)
P粉848442185

You can do this based on the string provided, but it's easier if you provide the email address as a separate property on MyComponent.

Without changing the components, I would use some simple regex to get the email address from a string and then you can do whatever you want.

The following is a simple and incomplete regular expression example:

const SUPER_SIMPLE_EMAIL_REGEX = /[a-z0-9.]{1,}@test.com/gi; // 不要使用这个

export function MyComponent({ myInput }: MyProps) {
   const match = myInput.match(SUPER_SIMPLE_EMAIL_REGEX);

  if (!match.length) {
    return (
      <div>
        {myInput}
      </div>
    );
  }

  const textWithoutEmail = myInput.replace(match[0], '');

  return (
    <div>
      <span>{textWithoutEmail}</span>
      <a href={`mailto:${match[0]}`} target="_blank">
        match[0]
      </a>
    </div>
  );

};

This is a very simplified solution, but I think you can use it in your case.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!