You can return a fragment with the text and a <strong> (or other element you style to make it bold, but remember accessibility if you do). When doing that, it may be best to always return a fragment even if you don't need one:
const truncateString = (str, num) => {
// Had to remove the optional chaining because the Babel used by
// Stack Snippets is **THAT** old.
if (str && str.length > num) {
// Have to use React.Fragment because the Babel used by
// Stack Snippets is **THAT** old.
return (
<React.Fragment>
{str.slice(0, num)} <strong>...read more</strong>
</React.Fragment>
);
} else {
return <React.Fragment>{str}</React.Fragment>;
}
};
const Example = () => {
return (
<div>
<div>Truncated: {truncateString("abcdefghijklmnopqrstuvwxyz", 10)}</div>
<div>Untruncated: {truncateString("abcde", 10)}</div>
</div>
);
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
You might make the "read more" clickable so it shows the remainder of the text (which strengthens the argument for making it a component). Rough sketch:
3条答案
按热度按时间fnvucqvd1#
You can return a fragment with the text and a
<strong>
(or other element you style to make it bold, but remember accessibility if you do). When doing that, it may be best to always return a fragment even if you don't need one:...but you don't technically have to:
Example:
A couple of other thoughts:
Rough sketch:
up9lanfz2#
看看这个,希望它适合你。
7tofc5zh3#
这里可以使用的是
希望能成功