试图使用 lodash 的去抖动去抖动输入,但下面的代码给了我未定义的值。
const { debounce } from 'lodash'
class App extends Component {
constructor(){
super()
this.handleSearch = debounce(this.handleSearch, 300)
}
handleSearch = e => console.log(e.target.value)
render() {
return <input onChange={e => this.handleSearch(e)} placeholder="Search" />
}
}
最佳答案
这是因为 React 端的事件池。
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
class App extends React.Component {
constructor() {
super()
this.handleSearch = debounce(this.handleSearch, 2000);
}
handleSearch(event) {
console.log(event.target.value);
}
render() {
return <input onChange = {
(event)=>{event.persist(); this.handleSearch(event)}
}
placeholder = "Search" / >
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
https://reactjs.org/docs/events.html#event-pooling
关于javascript - react 去抖动得到 e.target.value 未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49081149/