如何使用 Rxjs 实现切换

How implement toggle with Rxjs

我正在学习 rxjs。我为 Dropdown 组件创建装饰器 "toggleable"。一切正常,但我不喜欢它。如何删除条件 "toggle/hide".

使用 rxjs,react.js,重构。 它是 Dropdown 组件的可切换装饰器。

export const toggleable = Wrapped => componentFromStream((props$) => {
// toogleHandler  called  with onClick
  const { handler: toogleHandler, stream: toogle$ } = createEventHandler();
// hideHandler called with code below
  const { handler: hideHandler, stream: hide$ } = createEventHandler();

  const show$ = Observable.merge(
    toogle$.mapTo('toogle'),
    hide$.mapTo('hide'))
          .startWith(false)
          .scan((state, type) => {
            if (type === 'toogle') {
              return !state;
            }
            if (type === 'hide') {
              return false;
            }

            return state;
          });


  return props$
    .combineLatest(
      show$,
      (props, show) => (
        <Wrapped
          {...props}
          show={show}
          onToggle={toogleHandler}
          onHide={hideHandler}
        />
      ));
});

它是下拉按钮的装饰器

  // hideHandler caller
        class Foo extends Component {
            constructor(props) {
              super(props);
              this.refButton.bind(this);
              this.documentClick$ = Observable.fromEvent(global.document, 'click')
                .filter(event => this.button !== event.target)
                .do((event) => { this.props.onHide(event); });
            }

            componentDidMount() {
              this.documentClick$.subscribe();
            }
            componentWillUnmount() {
              this.documentClick$.unsubscribe();
            }
            refButton = (ref) => {
              this.button = ref;
            }
        }

您可以通过将 toggle$/hide$ 映射到先前状态的函数来实现无条件显示 $:

const show$ = Observable.merge(
    toggle$.mapTo(prev => !prev),
    hide$.mapTo(prev => false))
        .startWith(false)
        .scan((state, changeState) => changeState(state));

您可以做的另一项改进是可切换的实施。您可以使用 recompose mapPropsStream:

而不是使用 recompose componentFromStream
export const toggleable = mapPropsStream(props$ => {
    const { handler: toogleHandler, stream: toogle$ } = createEventHandler();
    const { handler: hideHandler, stream: hide$ } = createEventHandler();
    const show$ = Observable.merge(
        toggle$.map(() => prev => !prev),
        hide$.map(() => prev => false))
            .startWith(false)
            .scan((state, changeState) => changeState(state));

    return props$
        .combineLatest(
            show$,
            (props, show) => ({
                ...props,
                show
                onToggle: toogleHandler
                onHide: hideHandler
            })
        );
});