Sha*_*hai 3 javascript ecmascript-6 reactjs
试图使用lodash的反跳来反跳一个输入,但是下面的代码给了我undefined值。
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" />
}
}
Run Code Online (Sandbox Code Playgroud)
发生这种情况是因为React端有事件池。
SyntheticEvent已合并。这意味着在调用事件回调之后,将重新使用SyntheticEvent对象,并且所有属性都将无效。这是出于性能原因。因此,您不能以异步方式访问事件。
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'));Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
https://reactjs.org/docs/events.html#event-pooling
| 归档时间: |
|
| 查看次数: |
1197 次 |
| 最近记录: |