当我尝试突出显示在DIV中找到的单词时,它会找到该单词,但是会同时删除一些单词,例如,当我搜索“ a”时,它会突出显示“ a”但也删除了“这是”一词。我已经在自己的帖子中附加了代码。有可能修复它吗?
<div id="app2"> </div>
<script type="text/babel">
class MyApp extends React.Component {
constructor() {
super();
this.state = {
inputValue: "",
fields: [<Ta />]
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
let object = this.refs.Progress1;
let fields = this.state.fields;
let searchBarText = e.target.value;
let divText = object.textContent;
let idx = divText.indexOf(searchBarText);
if (idx >= 0) {
let newText = [
divText.substring(0, searchBarText),
<strong>{divText.substring(idx, idx + searchBarText.length)}</strong>,
divText.substring(idx + searchBarText.length)
];
this.setState({ inputValue: searchBarText, fields: newText });
} else {
this.setState({ inputValue: searchBarText, fields: fields });
}
}
render() {
return (
<div>
<input
type="text"
className="input"
onChange={this.handleChange}
placeholder="Search..."
/>
<p ref="Progress1" id="try">
<p>{this.state.fields}</p>
</p>
</div>
);
}
}
class Ta extends React.Component {
render() {
return <p id="Progress1">this is a dog</p>;
}
}
ReactDOM.render(<MyApp />, document.getElementById("app2"));
</script>
<style>
strong
{
color:red;
}
</style>
答案 0 :(得分:0)
您只是错过了一个小细节:
替换:
let newText = [divText.substring(0, searchBarText),
<strong>{divText.substring(idx, idx + searchBarText.length)}</strong>, divText.substring(idx + searchBarText.length)];
成为:
let newText = [divText.substring(0, idx),
<strong>{divText.substring(idx, idx + searchBarText.length)}</strong>, divText.substring(idx + searchBarText.length)];