Onsen UI QUICK START FOR REACT

前端之家收集整理的这篇文章主要介绍了Onsen UI QUICK START FOR REACT前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

To use Onsen UI in React apps,Onsen UI Core and React Components should be installed to the project. These modules can be installed via NPM package:onsenuiandreact-onsenui.

To quickly setup the project,Monaca CLI will solve all dependencies including TypeScript,Webpack and polyfills if necessary.

Using Onsen UI toolkit - Monaca CLI

$ npm install -g monaca # Install Monaca CLI - Onsen UI toolkit
$ monaca create helloworld # Choose React template
$ cd helloworld; monaca preview # Run preview,or "monaca debug" to run on your device

Download via npm

# The "react-onsenui" library requires the "onsenui" library.
$ npm install --save-dev onsenui react-onsenui

Use Kitchensink Code

Onsen UI React Components Kitchensinkcontains almost all components in Onsen UI as one application package.Link to Kitchensink Demo.

The code in this example is transpiled using Babel and bundled withBrowserify.

Loading Onsen UI for React

Onsen UI for React is an extension to Onsen UI core,a Web components based UI framework. You need to load the following two JavaScript modules.

  • Onsen UI Core (GitHub)
  • Onsen UI for React Extension (GitHub)

You can load with a normal<script>tag as follows:

<script src="react.js"></script>
"react-dom.js">"onsenui.js">"react-onsenui.js">"https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js">script>

Or,you can use React and Onsen UI from npm with CommonJS module system like Browserify or Webpack. In this case,use theonsenuiandreact-onsenuipackages,in addition toreactandreact-domnpm packages. In the example belowonscontains Onsen UI core instance,andOnscontains React components.

var React = require('react');
var ReactDOM = 'react-dom');
var ons = 'onsenui');
var Ons = 'react-onsenui');

Alternatively,you can also useES6 importsto specify the modules you want to use inreact-onsenuipackage.

import {Page,Toolbar,Button} from 'react-onsenui';

Onsen UI HelloWorld with React

To get started,let’s create a simple Hello World application. The following sample code is a React version of Onsen UI HelloWorld.

<!DOCTYPE html>
html lang="en">
  head>
    Meta charset="utf-8" />
    link rel="stylesheet" href="css/onsenui.css">
    "css/onsen-css-components.css">
    script>
    script>
  head>
  body>
    div id="app">div>
  body>
  type="text/babel"> var App = React.createClass({ handleClick: function() { ons.notification.alert('Hello world!'); },render: ) { return ( <Ons.Page> <Ons.Button onClick={this.handleClick}>Tap me!</Ons.Button> </Ons.Page> ); } }); ReactDOM.render(<App />,document.getElementById('app')); html>

This example is loading the following JS libraries,react.js,monospace; vertical-align: baseline;">react-dom.js,monospace; vertical-align: baseline;">onsenui.jsandreact-onsenui.js. For stylesheets,it is loadingonsenui.cssandonsen-css-components.csswhich are bundled in Onsen UI distribution package. To know the details about Onsen UI stylesheets,please refer to ourStyle Sheets Guidedocument.

<link rel="stylesheet" href="css/onsenui.css">
<"css/onsen-css-components.css">

In<body>tag,there is only a<div>tag havingappid. This is where React will render the content into,and you can see it in the very bottom of JS code.

Also notice<script></script>tag hastext/babeltype. This means this script is not a pure JavaScript that browser supports (most commonly ECMAScript5),but is a ECMAScript6 (ES2015) with JSX format.Babelwill transpile this code into ES5 in the browser. To get better performance,we can use node.js to transpile the code.

Inside the script,monospace; vertical-align: baseline;">React.createClass()function defines a React Component calledApp. It has one method calledrender,and this is the function that is called when the app is rendered. The returning object is described inJSX,which is a XML like language that extends JavaScript. In this case,it is returning<Ons.Page>component that has an<Ons.Button>component. TheonClickprop is used to call thehandleClickmethod when the user taps the button.

return (
  <Ons.Page>
    <Ons.Button onClick={this.handleClick}>Tap me!</Ons.Button>
  </Ons.Page>
);

As you can see in this example,all<Ons.*>components are React Components,and they are loaded byreact-onsenui.js. Click here to see our fullOnsen UI React Components Reference.

Putting together,whenindex.htmlis loaded into the browser,it will compile JSX code,inject into the body,and render the content.

This is a basic introduction of how Onsen UI and React works together. If you want to further learn React,we recommend to read the officialReact docs.

Creating a page

The root of a page is created using the<Page>element. It covers the whole screen and is used as a container for the other elements.

Adding a toolbar

A toolbar is defined as a<Toolbar>or<BottomToolbar>component. Here is the typical example of a toolbar.

Page renderToolbar={() =>
  Toolbar>
    className="left">
      BackButton>BackBackButton>
    div>
    "center">Title"right">
      ToolbarButton>
        Icon icon="md-menu" />
      ToolbarButton>
    Toolbar> }
>
  Static page app
Page>

The toolbar is divided into 3 sections that can be specified as class names (left,monospace; vertical-align: baseline;">center,monospace; vertical-align: baseline;">right). You can use<Icon>to display an icon,<ToolbarButton>or<BackButton>to place an button,or insert any HTML content.

Event Handling

Onsen UI components are capable of handling events. For instance,you can catch a tap event by using theonClickprop,or text input change with theonChangeprop.

class MyPage extends React.Component {
  handleClick() {
    ons.notification.alert('Hello,world!');
  }
  render() {
    return() (
      Page> Button onClick={this.handleClick}>Click me!Button> Page>
    );
  }
}

Theonsobject

Onsen UI not only provides custom elements,it also exposes an object calledonswith a lot of useful functions attached to it. Theonsobject is part of the core library and can be imported in the bindings.

The following example usesons.ready(fn)which waits until the app is completely loaded before executing a callback function. Inside the callback,it is callingons.notification.alert()to display a alert dialog.

ons.ready() {
  // Onsen UI is now initialized
  ons.notification.alert('Welcome to Onsen UI!');
});

See alsoons.platform,ons.notificationandons.orientationfor more utilities.

Importingonsobject in React

Simply use ES6 imports:

import ons `onsenui`;
import { platfrom,notification } `onsenui`;

Adding page content

For a full list of components please check thereference page.

Form elements

Onsen UI provides a rich set of form components. Apart from<Button>,<Switch>and<Range>,perhaps the<Input>component is the most common one since it supports different shapes:checkBox,monospace; vertical-align: baseline;">radio,monospace; vertical-align: baseline;">password,etc.

<Input
  value={this.state.text} float
  onChange={(event) => { this.setState({text: event.target.value})} }
  modifier='material'
  placeholder='Username' />

<Input type="checkBox" checked={this.state.checked} onChange={this.onChange} />

Lists

Lists are a very common pattern in mobile apps and thus Onsen UI provides abstraction for it. By using<List>,<ListItem>and<ListHeader>you can make simple or complex lists of items. Every list item is by default divided into three sections,just like<Toolbar>,and some CSS classes are provided for default styles (list__item__icon,monospace; vertical-align: baseline;">list__item__thumbnail,monospace; vertical-align: baseline;">list__item__titleandlist__item__subtitle).

List dataSource={['Row 1','2']} renderRow={(row, idx) => (
    ListItem modifier={idx === this.state.data.length - 1 ? 'longdivider' : null}>
      "left">
        "md-face" "list__item__icon" />
      div>
      "center">
        span "list__item__title">{row}span>
        "list__item__subtitle">Subtitlespan>
      label "right">
        Switch />
      label>
    ListItem>
  )}
/>
Lazy repeat

For cases when the list can contain thousands of items,<LazyRepeat>component will enhance the performance by loading and unloading items depending on the current scroll.

Layouting

Onsen UI provides a grid system to place your elements in the screen. The grid system divides the screen into rows and columns,just like a spreadsheet. The width and height of each grid is adjustable,and you can also condense two or more grids in a row or column,into one grid.

The layout can be performed by combining<Col>and<Row>components. The width and height can be adjusted in a flexible way.

Grid is not necessary in general for list items. Special layout is provided for list items based on flat iOS and Material Design specification. Seelistsection for more information.

Control and visual components

Other components from different categories are available to complete the developer needs.

<Carousel>and<CarouselItem>components provide a simple carousel that can optionally be overscrollable and fullscreen.

Pull-hook

A very common way to check for updates in apps is given by the<PullHook>component,which enables a simple “pull to refresh” functionality.

Speed-dial

<SpeedDial>and<SpeedDialItem>are just a set of floating action buttons (<Fab>) that can be shown or hidden by the user. This components are mainly used in Material Design.

Progress

<ProgressBar>and<ProgressCircular>display the loading progress like it’s done in Material Design. Two modes are supported: display the exact progress that is provided to the component or display an indeterminated progress.

Icons

Onsen UI bundles three icon packs to be used with<Icon>component:

In general,Ionicons are good for iOS apps while the Material Icons work best for apps using Material Design.

Gesture detector

It is a common use case to detect a finger gesture and do a specific task. Onsen UI utilizes a modified version ofHammer.jsfor gesture detection. The Gesture Detector class (Hammer.js) is exposed inons.GestureDetectorobject.

var divGD = ons.GestureDetector(document.querySelector('#my-div'));
divGD.on('dragup dragdown',event) {
  console.log('drag Y axis');
});

If you want to use another library for this purpose and have any conflict,Onsen UI gesture detectors can be disabled easily:

ons.GestureDetector('#my-menu')).dispose(); // Remove event listeners from the menu

Dialogs

There are multiple types of dialog components available in Onsen UI:<Dialog>for displaying a page inside a centered dialog;<AlertDialog>for displaying a simple message inside an alert style dialog;<Popover>for showing some content next to a specified element or a context menu; and<Modal>for displaying a fullscreen dialog that forbids user interaction.

Apart from that,196);">ons.notificationobject offers a more handy solution for simple dialogs:

ons.notification.alert('Hello world!'); // Basic alert
ons.notification.confirm('Are you ready?'); // OK - Cancel buttons
ons.notification.prompt('What is your name?'); // Text input

Multiple page navigation

In Onsen UI there are three navigation patterns based on three different components:<Navigator>,<Tabbar>and<Splitter>. These components supply “frames” able to change their inner content. The content of these frames will normally be<Page>components but it is also possible to nest navigation components in order to combine them.

More information is provided in the “Docs” tab of the Live Example section of each component.

The main pattern uses<Navigator>component to provide a stack where you can push and pop pages with transition animations. This is the basic and most used navigation pattern and can be combined with the other two.

Use this pattern when you have a sequential flow where a page depends on the prevIoUs one. Data can be optionally passed from one page to another.

Tabbar

In this case,by using<Tabbar>component a visible tabbar is displayed at the bottom or the top of the page with tabs associated to different pages. The component will load content depending on the selected tab (<Tab>). This pattern is commonly used to sepparate different sections in the app.

A menu can be added using the<Splitter>component. For small devices it can be used to create a swipeable menu,but for larger screens it can automatically display a column layout.

Splitter provides two frames that can load different content:<SplitterSide>and<SplitterContent>. A common usecase is to show a list in the side menu where each item loads a different page in the content frame. Notice that loading new content in any of these frames will completely remove the prevIoUs loaded content. For more complex navigation consider nesting<ons-navigator>inside<ons-splitter-content>.

Using Modifier

Modifier is a cross-component way to provide customizability for Onsen UI components. When a component is defined with amodifier,it will have a separate class namespace so that you can apply custom styles to the component. Also,some components have several preset modifiers to change the appearance.

For example,each of the following buttons have different look. To change modifiers dynamically,please manipulatemodifierattribute from JavaScript.

"quiet">QuietButton>
"light">Light"large">Large"cta">Call To Action"material">Material DesignButton>

Cross platform styling

Onsen UI components are automatically styled depending on the platform where the app runs. You can easily test this feature with your browser Dev Tools by switching between iOS and Android views.

Automatic styling simply appliesmodifier="material"to the components whenons.platform.isAndroid()is true. You can disable this feature by runningons.disableAutoStyling()right after includingonsenui.js(i.e. before the app is initialized). If you disable it you may need to manually specifymodifier="material"in every component you want to display with Material Design. You can also specifydisable-auto-stylingattribute in specific components that you don’t want to auto style.

Some tools are provided to give a more accurate customization.

Platform utilities

ons.platformobject is available with methods such asons.platform.isIOS(),monospace; vertical-align: baseline;">ons.platform.isWebView(),etc.

You can set a platform withons.platform.select('android'),for example,in order to display Material Design on every platform. This must be called before the app is initialized (right after includingonsenui.js).

With this,you can display<Fab>for Material Design and other type of button for iOS flat design.

Icons shortcut

<Icon>component provides a shortcut to make auto styling easier:

"ion-navicon,material:md-menu" size="24px,material:20px" />

The second icon will be displayed whenmaterialmodifier is present (other modifiers can be used).

CSS Definitions

Onsen UI styles are defined inonsen-css-components.css. They are written in theStylusformat.

onsenui.cssis a core CSS module that defines styles for the custom elements. The source code exists undercore/cssdirectory.onsen-css-components.csscontains CSS definitions for CSS components. The source code exists incss-components/components-src/stylus.

You can also useOnsen CSS Componentsto customize pre-defined colors. After the customization,you can download and replace to the existingonsenui-css-components.cssto reflect the changes.

Overriding CSS style

If you want to apply a different style to a specific component,you can usemodifierattribute to override its style definition.

ons-button "thick">Thick Buttonons-button>

Then,write the appropriate style code under the style tag or in the css file.

style> .button--thick { border: 10px; } style>
原文链接:https://www.f2er.com/react/305460.html

猜你在找的React相关文章