在react中访问回调中的 event.target

IT技术 javascript reactjs
2021-03-15 19:57:54

我有以下类片段:

constructor(props) {
    super(props);

    this.timeout = null;
}

search = (e) => {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(
        function(){ console.log(e.target); },
        500
    );
}

<input 
    type="text" 
    placeholder="Search by title or author" 
    onKeyPress={this.search} />

我无法获得设置的超时时间来打印事件的值,有什么我应该做但我没有做的事情吗?

5个回答

合成事件

根据DOC

SyntheticEvent 被合并。这意味着 SyntheticEvent 对象将被重用,并且在调用事件回调后所有属性都将被取消。这是出于性能原因。

例子:

function onClick(event) {
   console.log(event.type); // => "click"
   const eventType = event.type; // => "click"

   setTimeout(function() {
      console.log(event.type); // => null
      console.log(eventType); // => "click"
   }, 0);    
}

如何访问回调中的值?

将值存储在变量中:

如果要访问超时回调函数中的值,则将该值存储在变量中并使用该变量而不是直接使用事件对象。

function onClick(event) {

   console.log(event.type); // => "click"

   const { type } = event;

   setTimeout(function() {
      console.log(type);   // => click
   }, 0);    
}

使用 event.persist():

如果您想以异步方式访问事件属性,您应该对事件调用event.persist(),这将从池中删除合成事件并允许用户代码保留对事件的引用。

function onClick(event) {

   event.persist();

   console.log(event.type); // => "click"

   setTimeout(function() {
      console.log(event.type); // => click
   }, 0);    
}

试试这个:

search = (e) => {
e.persist();
clearTimeout(this.timeout);
this.timeout = setTimeout(
    function(){ console.log(e); alert(e) },
    500
);

}

从您的代码来看,我认为您正在使用babel-plugin-transform-class-properties在这种情况下,您不需要构造函数部分。

没有看到您的 onKeypress 方法很难说,但这可能是一个绑定问题。尝试在构造函数中绑定您的搜索。

constructor (props) {
    super(props);

    this.timeout = null;
    this.search = this.search.bind(this);
}
我更新了代码以包含 onkeypress 方法调用
2021-04-28 19:57:54

你要设为timeoutas 状态吗?

我的建议是这样的

constructor(props) {
    super(props);
    this.state = {
       timeout: null
    }
}

search = (e) => {
    clearTimeout(this.state.timeout);
    const timeout = setTimeout(
        function(){ console.log(e.target); },
        500
    );
    this.setState({timeout: timeout})

}

合成事件 - react

注意:从 v17 开始, e.persist() 不会做任何事情,因为 SyntheticEvent 不再被合并。

在 React v17 之后,SyntheticEvent 不再取消事件。