【发布时间】:2020-01-11 23:31:05
【问题描述】:
我想在“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 在结果中返回多个元素,您必须遍历结果数组。为此使用
for in或for of循环。
标签: javascript reactjs api fetch