小编典典

Rxjs在React文本输入组件上反跳

reactjs

我有以下反应成分

<input className={styles.incSrchTextBox} type="text" name="search" placeholder="Search.."
   onChange={this.onChange} />


onChange(e) {
    const newText = e.target.value;
    console.log(newText);
    this.setState({ searchText: newText });
}

我该如何在rxjs上使用反跳功能?


阅读 257

收藏
2020-07-22

共1个答案

小编典典

您将需要从更改事件中爬出可观察到的位置(例如使用Subject),然后对此进行反跳。

这是为您提供功能齐全的示例:

class Search extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      search: '',

      debounced: '',

    };

    this.onSearch$ = new Rx.Subject();

    this.onSearch = this.onSearch.bind(this);

  }

  componentDidMount(){

    this.subscription = this.onSearch$

      .debounceTime(300)

      .subscribe(debounced => this.setState({ debounced }));

  }



  componentWillUnmount() {

    if (this.subscription) {

      this.subscription.unsubscribe();

    }

  }



  onSearch(e) {

    const search = e.target.value;

    this.setState({ search });

    this.onSearch$.next(search);

  }



  render() {

    const { search, debounced } = this.state;

    return (

      <div>

        <input type="text" value={search} onChange={this.onSearch} />

        <div>debounced value: {debounced}</div>

      </div>

    );

  }

}



ReactDOM.render(

  <Search />,

  document.getElementById('root')

);


<script src="https://unpkg.com/[email protected]/bundles/Rx.min.js"></script>

<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="root"></div>
2020-07-22