我正在尝试使用搜索栏搜索组件中的文本,我是否可以这样做?
class App extends React.Component {
render() {
return (
/**search the text inside this DIV**/
<div> this is a dog. </div>
)
}
}
谢谢:)
答案 0 :(得分:0)
组件内部的文本是纯标记还是在组件状态内控制?
如果是纯标记,则必须与dom交互-您可以使用refs做些事情:
https://reactjs.org/docs/refs-and-the-dom.html
无论哪种情况,无论是受控组件还是标记,您都必须以某种方式获取该内部文本,并将其传递给连接到搜索栏的事件处理程序。从那里开始,问题是在文本内搜索的最佳方法。我会留给你(正则表达式等)
答案 1 :(得分:0)
这是我实施的方式
def testfunc(ar):
ar.sort();
count = i = 0
while i + count < len(ar) - 1:
if ar[count + i] == ar[count + i + 1]:
count += 1
i += 1
return count
更新:如果div和搜索栏位于两个没有父子关系的React组件中,我将按以下方式实现它:
class App extends React.Component {
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log(e.target.value); // your search bar text
let object = this.refs.Progress1; // get your div element using refs
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;
let divText = object.textContent;
if (divText.includes(searchBarText)) {
console.log("the div text contains your search text");
} else {
console.log("the div text doesn't contain search text");
}
}
render() {
return (
<div>
<input type="text" className="input" onChange={this.handleChange} placeholder="Search..." />
<div ref="Progress1">
this is a dog. ...
</div>
</div>
);
}
}
具有Class A
div
class A extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<div id="myDiv">
this is a dog. ...
</div>
</div>
);
}
}
具有搜索栏
class B
如果两个类/组件之间存在父/子关系,则应依靠在父和子之间传递的道具,请参见此问题的示例:How to get refs from another component in React JS
答案 2 :(得分:0)
如果有人在React Hook中搜索操作方法。这是给你的:
import React, { useState, useRef } from "react";
export default function App() {
const [text, setText] = useState("");
const [isFound, setFound] = useState(false);
const paragraphEl = useRef(null);
const handleInput = (e) => {
setText(e.target.value);
const paragraphText = paragraphEl.current.textContent;
if (e.target.value !== "" && paragraphText.includes(e.target.value)) {
setFound(true);
} else {
setFound(false);
}
};
return (
<div>
<h1>Search text</h1>
<input
type="text"
placeholder="Type here"
value={text}
onChange={handleInput}
/>
<p ref={paragraphEl}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
</p>
{isFound && <p style={{ color: "green" }}>We found it</p>}
</div>
);
}