html - 显示带有空格和 JSX 的数组
问题描述
这是我写的代码。说有一句话“你好,请以@followme的身份关注我们”。这个函数会做的是找到包含“@”的单词,然后再次返回句子,尽管 @ 将被链接。如果我使用 .join(" ") 加入此数组,则 JSX 元素将显示为 [object, object] 因此作为修复,我已在数组中每隔一个索引添加一个空格。
我的问题是这行得通吗?我是否错过了一些如此简单的事情,可以让我的生活更轻松,很想知道!谢谢
---- 作为编辑,如果我没有在数组中添加额外的空格或不使用 .join,那么这句话实际上就是一个词......
const getInstagram = props => {
//Split sentence into an array
let test = props.split("@" +1).pop().split(" ");
let one;
//Get the word that contains @
test.map(word => {
if (word.includes("@")) {
one = word;
}
});
//Gets the array position
let position = test.indexOf(one);
test.splice(position);
if (position >= 0) {
let line = <a href={`https://instagram.com/${one}`}>{one}</a>
test.splice(position,0,line)
}
for(let i = 0; i < test.length; i++) {
test.splice(i++,0, " ");
}
return (
<p style={{ opacity: 1 }}>
{test}
{console.log(test)}
</p>
);
};
解决方案
保留输入短语的空白的另一种方法是,允许提取“@anchors”并将其包装在<a>
元素中,这是通过 a 扫描输入字符串for-loop
并在遇到锚子字符串时提取和包装锚子字符串,如下所示:
function ExtractAnchors(phrase) {
const parts = [];
/* Iterate characters of phrase */
for (let i = 0, j = 0; j < phrase.length; j++) {
/* If character is "@", extract the anchor */
if (phrase[j] === "@") {
/* Add string from prior index to start of anchor */
parts.push(phrase.substring(i, j));
/* Find end-index of the anchor */
let k = j;
while (k < phrase.length && phrase[k] !== " ") {
k++;
}
/* Extract the actual anchor substring from start and end indicies */
const anchor = phrase.substring(j, k)
parts.push(<a href={`https://instagram.com/${anchor}`}>{anchor}</a>);
/* Update indicies to end of extracted anchor */
j = k;
i = k;
} else if (j === phrase.length - 1) {
if (i !== j) {
/* Edge case to ensure whole string is collected if no anchor
or chracters exist after an anchor */
parts.push(phrase.substring(i, j + 1));
}
}
}
return parts;
}
这可以通过以下方式使用,其中所有情况都按预期工作:
<div>
<p>Plain string:</p>
{ExtractAnchors("Follow us")}
<p>String with whitespaces and single anchor:</p>
{ExtractAnchors("Follow us at @foo now")}
<p>String with whitespaces, multiple anchors, one at end of phrase:</p>
{ExtractAnchors("Follow us at @foo now or @bar")}
<p>String with whitespaces, multiple anchors, one at start of phrase:</p>
{ExtractAnchors("@foo or @bar are good to follow")}
<p>Empty string:</p>
{ExtractAnchors("")}
</div>
这是一个工作示例-希望对您有所帮助!
推荐阅读
- nuxt.js - 当所有人都可以进行静态站点生成时,为什么我会选择 Gridsome/Gatsby 而不是 Nuxt/Next?
- angular - NullInjectorError:没有 SwUpdate 的提供者!运行 ng 测试时
- prolog - Prolog:语法错误:文件过程意外结束“(?-A)”不存在
- keras - 使用深度学习卷积神经网络的手势识别
- typescript - 为什么在这个对象类型交集的结果中,`constructor` 属性的类型与`Function` 相交?
- delphi - 根据 TreeView 中检查的项目创建 TabSheet 和 Frame
- docker - 如何在 Kubernetes 的 Pod 之间传输文件?
- xml - 如何为自定义对象检测创建自己的 Haar 级联分类器?
- java - AWS SES 审计
- java - GLSL 统一变量未更新