聆听反应日选择器输入的“更改”事件

问题描述 投票:1回答:1

我正在使用react-day-picker库在我的网站上显示日期选择器。我想听听日期何时更改。我知道可以将onDayChange挂钩添加到DayPickerInput组件中,但是我想听听组件外部的更改。

示例:(https://codesandbox.io/s/react-day-picker-base-mpcqy

import React from "react";
import ReactDOM from "react-dom";
import DayPickerInput from "react-day-picker/DayPickerInput";

import "react-day-picker/lib/style.css";

function Example() {

  return (
    <div>
      <h3>DayPickerInput</h3>
      <DayPickerInput placeholder="DD/MM/YYYY" format="DD/MM/YYYY" />
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById("root"));

var input = document.getElementsByTagName("input")[0];
input.addEventListener("change", () => {
  console.log("changed");
});

我希望更改处理程序被解雇。我不确定为什么不是这样。如何聆听价值变化?

reactjs react-day-picker
1个回答
1
投票

您可以在react-day-picker documentations中看到您问题的答案

您应通过以下方式将事件处理程序传递给DayPickerInput组件:

function Example() {
  const [value, setValue] = useState(undefined);
  handleDayChange(day) {
    setValue(day);
  }

  return (
    <div>
      <h3>DayPickerInput</h3>
      <DayPickerInput
       placeholder="DD/MM/YYYY" 
       format="DD/MM/YYYY"
       onDayChange={day => handleDayChange(day)}
      />
    </div>
  );
}

这是侦听事件的唯一方法。另外,您应该知道直接更改DOM是非常糟糕的做法。

并且如果要使value可以全局访问,则应使用React的context APIRedux。 (状态管理工具)

© www.soinside.com 2019 - 2024. All rights reserved.