简体   繁体   English

Datepicker附加到React输入组件

[英]Datepicker attached to a React input component

In case of absence of native <input type="date"> support, I'd like to polyfill all the date inputs with datepicker widgets; 如果没有本机<input type="date">支持,我想用datepicker小部件填充所有日期输入; for example, jQuery UI datepickers . 例如, jQuery UI datepickers

See the demo here. 请在此处查看演示 In Google Chrome it renders native date inputs, while in Firefox (v32.0.3) the jQuery UI widgets get deployed. 在Google Chrome中,它会呈现原生日期输入,而在Firefox(v32.0.3)中,会部署jQuery UI小部件。 That's exactly where I'm having a problem. 这正是我遇到问题的地方。 All the manual changes in the input (keyboard edits) get reflected in the datepicker widget just fine. 输入中的所有手动更改(键盘编辑)都会很好地反映在datepicker小部件中。 However, the other way around, if I select a day in the widget calendar, the new value doesn't get picked up by the underlying React component. 但是,反过来说,如果我在窗口小部件日历中选择一天,则新值不会被底层的React组件拾取。 In the demo you'll notice that in Chrome, on a date selection, the other date gets auto-adjusted. 在演示中,您会注意到在Chrome中,在日期选择中,另一个日期会自动调整。 That functionality is broken for datepickers in Firefox. Firefox中的datepickers打破了这个功能。 React has no idea that values change. React不知道价值观会发生变化。

Following this advice , I've added 遵循这个建议 ,我补充道

componentDidMount: function(e) {
    this.getDOMNode().addEventListener(
        'change',
        function (e) { console.dir(e); }
    );
},

to my DateInput component class. 到我的DateInput组件类。 However, it never gets called on widget selections. 但是,它永远不会被调用小部件选择。 How can I make it work? 我怎样才能使它工作?

The full non-compressed source code of the demo linked above is available here. 上面链接的演示的完整非压缩源代码可在此处获得。

The solution is doing everything over jQuery, and not over the DOM directly: 解决方案是通过jQuery完成所有工作,而不是直接通过DOM:

var isPolyfilled = function () {
        return (window && window.$ && window.$.datepicker);
    };

module.exports = React.createClass({
    ...

    componentDidMount: function () {
        setTimeout(function () {
            if (isPolyfilled()) {
                window.$(this.getDOMNode()).datepicker();
                window.$(this.getDOMNode()).on('change', this.handleEdit);
            }
        }.bind(this), 500);
    },

    componentWillUnmount: function () {
        if (isPolyfilled()) {
            window.$(this.getDOMNode()).off();
        }
    }

    ...
};

The complete source code is on GitHub. 完整的源代码在GitHub上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM