【发布时间】:2019-06-08 18:53:51
【问题描述】:
我是新来的反应。我正在尝试将react-highlight-words 包含在我的应用程序中以搜索文本。所以我创建了一个简单的搜索文本框,我们可以在其中搜索文本。现在我的文本框在SearchBar.js 内,而荧光笔组件代码在Highlighter.js 内,我使用componentDidMount 和componentWillRecieveProps 从父SearchBar 组件中检索testHighlight 值。但它不打印值,所以我无法在Highlighter 内部传递。
你能告诉我如何解决它,以便将来我自己解决它。
在下面提供我的沙箱和代码 sn-p。
https://codesandbox.io/s/4qp1p2zvl4
SearchBar.js
class SearchBar extends React.Component {
constructor() {
super();
this.state = {
testHighlight: {}
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log(e.target.value); // your search bar text
let object = document.getElementById("myDiv");
console.log(object.textContent); // your div text
// now that you have the two strings you can do your search in your favorite way, for example:
let searchBarText = e.target.value;
console.log("searchBarText --->", searchBarText);
let divText = object.textContent;
console.log("divText --->", divText);
if (divText.includes(searchBarText)) {
console.log("the div text contains your search text");
} else {
console.log("the div text doesn't contain search text");
}
// this.setState({ testHighlight: response.data });
this.setState({ testHighlight: searchBarText });
}
render() {
return (
<div>
<input
type="text"
className="input"
onChange={this.handleChange}
placeholder="Search..."
// highlightText={this.handleChange}
testHighlight={this.state.testHighlight}
/>
</div>
);
}
}
Highlighter.js
class Highlighter extends React.Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
console.log("componentDidMount---->", this.props.testHighlight);
}
componentWillRecieveProps(nextProps) {
console.log("componentWillRecieveProps---->", this.props.testHighlight);
if (this.props.testHighlight !== nextProps.testHighlight) {
this.setState({ testHighlight: nextProps.testHighlight });
}
}
render() {
return (
<div>
<Highlighter
highlightClassName="YourHighlightClass"
//searchWords={["and", "or", "the"]}
searchWords={this.props.testHighlight}
autoEscape={true}
textToHighlight="The dog is chasing the cat. Or perhaps they're just playing?"
/>
</div>
);
}
}
【问题讨论】:
标签: javascript html reactjs redux material-ui