1

Дан следующий код на React.

export default class CallPage extends Component {
  state = {
    isVisible: false,
    prevBarId: "toolbar-hide",
    prevBoxId: "toolbox-hide",
    newBarId: "toolbar",
    newBoxId: "toolbox",
  };

  static defaultProps = {
    onMouseMove: () => {},
  };

  showToolElement = () => {
    this.setState(
      ({ isVisible }) => ({
        isVisible: !isVisible,
      }),
      () => {
        this.props.onMouseMove(this.state.isVisible);
      },
      console.log("it works"),
    );
  };
  render() {
    const isVisibleBar = this.state.isVisible
      ? this.state.newBarId
      : this.state.prevBarId;
    const isVisibleBox = this.state.isVisible
      ? this.state.newBoxId
      : this.state.prevBoxId;
    return (
      <div id="logged">
        <div id="session" onMouseMove={this.showToolElement}>
          <ToolBar visible={isVisibleBar} />
          <VideoHolder />
          <ToolBox visible={isVisibleBox} />
        </div>
      </div>
    );
  }

Суть в том, что при движении мыши он должен показывать невидимые блоки, а потом через заданное количество времени скрывать их снова. На данном этапе блоки появляются и исчезают на каждой новой координате мыши. Подскажите, как правильно прописать функцию showToolElement и setState, чтобы все работало как надо. Желательно, используя throttling.

1 ответ 1

2

Возможно, вам подойдет такое решение (можно использовать собственный debounce, можно установить lodash (npm i --save lodash), откуда подключить уже готовую функцию. В данном случае можно использовать опцию "leading": true, что позволит показать тулбар при первом срабатывании события, и скрыть только когда событие перестанет вызываться) :

function debounce(f, ms,leading) {
  let timer = null;
  return function (...args) {
    const onComplete = () => {
      f.apply(this, args);
      timer = null;
    }
    if(timer === null && leading) f.apply(this, args);
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(onComplete, ms);
  };
}
export default class CallPage extends Component {
  state = {
    isVisible: false,
    prevBarId: "toolbar-hide",
    prevBoxId: "toolbox-hide",
    newBarId: "toolbar",
    newBoxId: "toolbox",
  };

  static defaultProps = {
    onMouseMove: () => { },
  };

  showToolElement = debounce(() => {
    this.setState({
      isVisible: !this.state.isVisible
    })
  }, 5000, true);
  render() {
    const isVisibleBar = this.state.isVisible
      ? this.state.newBarId
      : this.state.prevBarId;
    const isVisibleBox = this.state.isVisible
      ? this.state.newBoxId
      : this.state.prevBoxId;
    return (
      <div id="logged">
        <div id="session" onMouseMove={this.showToolElement}>
          <ToolBar visible={isVisibleBar} />
          <VideoHolder />
          <ToolBox visible={isVisibleBox} />
        </div>
      </div>
    );
  }
}
2
  • Спасибо, действительно работает. Было бы совсем идеально, если бы Вы подсказали, как завернуть showToolElement в debounce, чтобы функция вызывалась не чаще чем в заданное количество секунд при mousemove 28 фев 2019 в 14:08
  • @АлисаГулий пожалуйста! Поправил ответ, теперь используется debounce 28 фев 2019 в 19:59

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.