2017-05-05 44 views
0

在ReactJS中執行緩衝輸入的正確方法是什麼?React中的緩衝輸入

也就是說,您有一個過濾器可以縮小(例如)一個元素,但在等待最後一個用戶輸入之後爲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

簡單的去抖動 – dfsq

回答

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"; 
    }); 
    }