How can I use javascript library such as moment.js in react native

后端 未结 5 2008
臣服心动
臣服心动 2021-02-06 20:13

What is the recommended way to use native javascript libraries in react native? Are there any specific restrictions?

相关标签:
5条回答
  • 2021-02-06 20:33

    If you specifically want to use moment.js in react or react native, have a look at react-moment, a react component for the moment library, at https://github.com/headzoo/react-moment.

    To use react-moment in react native, run:

    npm install --save moment react-moment
    

    Then in the file you want to use moment:

    import Moment from 'react-moment';
    

    Finally, use it as desired, for example:

    <Moment element={Text} fromNow>
        { post.datePublished }
    </Moment>
    

    The prop element={Text} is specifically for react native. It ensures that the resulting string is rendered in a Text component. Without this, react native would throw an error.

    0 讨论(0)
  • 2021-02-06 20:36

    Some of the moment methods work in React Native and others don't. I suspect it has to do with listeners.

    I can use moment for formatting:

    moment(new Date()).format("YYYY-MM-DD hh:mm:ss")
    

    But not for active formatting:

    moment(new Date()).format("YYYY-MM-DD hh:mm:ss").fromNow()
    
    0 讨论(0)
  • 2021-02-06 20:44

    Easy peasy! From the root of your project just run:

    npm install moment --save
    

    Then you can import it in your code:

    import moment from 'moment';
    var now = moment().format();
    

    The restrictions would be anything that tries to "reach out" to the browser (which doesn't exist in this context). That's why there's polyfills for things like XHR.

    The official documentation has examples on how to use the moment library

    0 讨论(0)
  • 2021-02-06 20:45

    It looks like as of right now, some npm modules are not compatible with the packager. Haven't really dug into why yet, but what I've been resorting to doing is having a vendor folder and copying over the web version but at the top specifically putting

    /** * @providesModule moment */

    And at the bottom changing it up to:

    module.exports = moment;

    Not sure if this is the correct way yet, but the packaging is still pretty new to everyone.

    0 讨论(0)
  • 2021-02-06 20:58

    to use a npm library just use this command with the respective library name

    npm install moment --save
    

    eg.) npm install {your library name here} --save

    then just import in your class and use

    import moment from 'moment';
    
    0 讨论(0)
提交回复
热议问题