5

我是 reactJS 的新手,我正在尝试使用纯flatpickrhttps://flatpickr.js.org,而不是 react-flatpickr)下面是我当前的代码。有关如何正确实施它的任何帮助?


import React, { Component } from "react"
import flatpickr from "flatpickr"

export default class Datepicker extends Component<IProps> {

  public render() {
    flatpickr(".datepicker")
    return (
        <div>
           <input type="text" className="datepicker" />
        </div>
    )
  }
}
4

1 回答 1

13

flatpickr需要传递给它的节点或选择器。在 React 中,为了引用 DOM,我们使用ref

为了处理事件和提供其他选项,您可以使用选项的第二个参数。

这是一个演示:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.datePicker = React.createRef();
  }
  onChange(selectedDates, dateStr, instance) {
    console.log(selectedDates);
  }
  componentDidMount() {
    flatpickr(this.datePicker.current, {
      onChange: this.onChange
    });
  }
  render() {
    return(
      <input type="date" ref={this.datePicker} />
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>


<div id="root"></div>

于 2018-12-19T11:34:44.773 回答