我想突出显示“text”元素句子中“highlight”元素中的单词。我可以成功突出显示一个句子,但无法将两个或多个句子连接在一起。我只能显示一个句子,并且用代码突出显示了该单词:
this.setState({
text: result[0].text,
highlight: result[0].highlight,
});
但一次不能超过多个句子。我想将 api 中尽可能多的句子与突出显示的单词动态连接起来。我尝试将状态设置为 text: result[].text
和 highlight: result[].highlight
但它给了我错误。正如您在 this sandbox 中看到的那样,只有当您执行 result[0].text
或 result[1].text
时,您会得到不同的结果,但我想连接中的所有句子动态api假设我将来会有更多句子。
react 代码如下所示:
import React, { Component } from "react";
import { render } from "react-dom";
import "./App.css";
const stripChars = word => word.replace(/[\W_]+/g, "");
class App extends Component {
state = {
text: "The gun is a dangerous weapon, don't kill anyone",
highlight: ["gun", "kill"]
// text: "",
// highlight: []
};
componentDidMount() {
fetch("https://api.myjson.com/bins/1ep1fh")
.then(res => res.json())
.then(result => {
console.log(result);
this.setState({
text: result[0].text,
highlight: result[0].highlight
});
});
}
render() {
const { text, highlight } = this.state;
const words = text.split(" ");
return (
<div>
{words.map((word, i) => (
<span key={i}>
<span
className={highlight.includes(stripChars(word)) && "highlight"}
>
{word}
</span>
</span>
))}
</div>
);
}
}
export default App;
CSS 文件:
.highlight{
background: red;
}
最佳答案
您可以在 api 调用中使用 Array.Map
和 join()
来迭代和平展数组:
componentDidMount() {
fetch("https://api.myjson.com/bins/1ep1fh")
.then(res => res.json())
.then(result => {
let texts = result
.map((el, i) => {
return el.text;
})
.join("");
let highlights = result
.map((el, i) => {
return el.highlight;
})
.join("").split(",");
console.log(highlights);
this.setState({
text: texts,
highlight: highlights
});
});
}
关于javascript - 如何连接从api接收到的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57866874/