2017-05-05 26 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') 
); 

上記のコメントと同様に、入力は累積的です。

t 
te 
tes 
test 

しかし、私が起こるしたいことは、まずそれをバッファリングすることであり、そしてちょうど送信:私は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"; 
    }); 
    } 
関連する問題