gpt4 book ai didi

javascript - react 去抖得到 e.target.value undefined

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:29:59 24 4
gpt4 key购买 nike

试图使用 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 端的事件池。

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

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 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49081149/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com