在ReactJS中进行缓冲输入的正确方法是什么?
也就是说,你有一个过滤器缩小(例如)一个元素,但在等待最后一个用户输入为 n 毫秒之前。
以下是您可以粘贴到jsfiddle的示例(对于未注册的用户,似乎没有“共享”功能?):
HTML:
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container"></div>
JavaScript的:
class Form extends React.Component {
render() {
return (
<div>
<Filter />
<Options />
</div>
);
}
}
class Filter extends React.Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.value === 'checkbox' ? target.checked : target.value;
// Buffer user input somehow, so that if you write "test"
// this would only log the value "test", instead of cumulatively:
// t
// te
// tes
// test
// If I use setTimeout(), it simply makes the cumulative input take effect with a delay, but still "t", "te", "tes", "test" instead of just "test"
console.log(value);
// This is the use case:
let elementsToHide = document.querySelectorAll("li:not([name*=" + value + "])");
Object.keys(elementsToHide).map(function(el) {
elementsToHide[el].style.visibility = "hidden";
});
}
render() {
return (
<input type="text" onChange={this.handleInputChange} />
);
}
}
class Options extends React.Component {
render() {
let examples = ["this", "is", "spartacus"];
return (
<ul>
{
examples.map(function(item) {
return <li key={item} name={item}>{item}</li>
})
}
</ul>
);
}
}
ReactDOM.render(
<Form />,
document.getElementById('container')
);
就像我在上面的评论中提到的那样,输入是累积的。所以如果我写test
那么它的作用是:
t
te
tes
test
但我想要发生的事情是首先缓冲它(例如1000毫秒),然后发送:
test
使用setTimeout()
只会在发送累积数据时延迟
t # appears after timeout
te # appears after timeout
tes # appears after timeout
test # appears after timeout
答案 0 :(得分:1)
你可以使用来自lodash的去抖动
constructor(props) {
super(props);
this.handleInputChange= _.debounce(this.handleInputChange, n); // where n is the numnber of milliseconds you want to wait
}
handleInputChange = (event) => {
const target = event.target;
const value = target.value === 'checkbox' ? target.checked : target.value;
// This is the use case:
let elementsToHide = document.querySelectorAll("li:not([name*=" + value + "])");
Object.keys(elementsToHide).map(function(el) {
elementsToHide[el].style.visibility = "hidden";
});
}