Onsen UI QUICK START FOR REACT

x33g5p2x  于2022-03-06 转载在 其他  
字(15.3k)|赞(0)|评价(0)|浏览(329)

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: onsenui and react-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 Kitchensink contains 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 with Browserify.

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.

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

<script src="react.js"></script>
<script src="react-dom.js"></script>
<script src="onsenui.js"></script>
<script src="react-onsenui.js"></script>
<script src="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 the onsenui and react-onsenui packages, in addition to react and react-dom npm packages. In the example below ons contains Onsen UI core instance, and Ons contains React components.

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

Alternatively, you can also use ES6 imports to specify the modules you want to use in react-onsenui package.

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">
    <link rel="stylesheet" href="css/onsen-css-components.css">
    <script src="react.js"></script>
    <script src="react-dom.js"></script>
    <script src="onsenui.js"></script>
    <script src="react-onsenui.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
  </head>
  <body>
    <div id="app"></div>
  </body>
  <script type="text/babel">
    var App = React.createClass({
      handleClick: function() {
        ons.notification.alert('Hello world!');
      },

      render: function() {
        return (
          <Ons.Page>
            <Ons.Button onClick={this.handleClick}>Tap me!</Ons.Button>
          </Ons.Page>
        );
      }
    });
    ReactDOM.render(<App />, document.getElementById('app'));
  </script>
</html>

This example is loading the following JS libraries, react.jsreact-dom.jsonsenui.js and react-onsenui.js. For stylesheets, it is loading onsenui.css and onsen-css-components.css which are bundled in Onsen UI distribution package. To know the details about Onsen UI stylesheets, please refer to our Style Sheets Guide document.

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

In <body> tag, there is only a <div> tag having app id. 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 has text/babel type. This means this script is not a pure JavaScript that browser supports (most commonly ECMAScript5), but is a ECMAScript6 (ES2015) with JSX format. Babel will transpile this code into ES5 in the browser. To get better performance, we can use node.js to transpile the code.

Inside the script, React.createClass() function defines a React Component called App. It has one method called render, and this is the function that is called when the app is rendered. The returning object is described in JSX, which is a XML like language that extends JavaScript. In this case, it is returning <Ons.Page> component that has an <Ons.Button> component. The onClick prop is used to call the handleClick method 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 by react-onsenui.js. Click here to see our full Onsen UI React Components Reference.

Putting together, when index.html is 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 official React 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>
    <div className="left">
      <BackButton>Back</BackButton>
    </div>
    <div className="center">Title</div>
    <div className="right">
      <ToolbarButton>
        <Icon icon="md-menu" />
      </ToolbarButton>
    </div>
  </Toolbar> }
>
  Static page app
</Page>

The toolbar is divided into 3 sections that can be specified as class names (leftcenter, and 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 the onClickprop, or text input change with the onChange prop.

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

The ons object

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

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

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

See also ons.platformons.notification and ons.orientation for more utilities.

Importing ons object in React

Simply use ES6 imports:

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

Adding page content

For a full list of components please check the reference 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: checkboxradiopassword, 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__iconlist__item__thumbnaillist__item__title and list__item__subtitle).

<List
  dataSource={['Row 1', 'Row 2']}
  renderRow={(row, idx) => (
    <ListItem modifier={idx === this.state.data.length - 1 ? 'longdivider' : null}>
      <div className="left">
        <Icon icon="md-face" className="list__item__icon" />
      </div>
      <div className="center">
        <span className="list__item__title">{row}</span>
        <span className="list__item__subtitle">Subtitle</span>
      </div>
      <label className="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. See list section 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 of Hammer.js for gesture detection. The Gesture Detector class (Hammer.js) is exposed in ons.GestureDetector object.

var divGD = ons.GestureDetector(document.querySelector('#my-div'));
divGD.on('dragup dragdown', function(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(document.querySelector('#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, ons.notification object 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 a modifier, 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 manipulate modifier attribute from JavaScript.

<Button modifier="quiet">Quiet</Button>
<Button modifier="light">Light</Button>
<Button modifier="large">Large</Button>
<Button modifier="cta">Call To Action</Button>
<Button modifier="material">Material Design</Button>

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 applies modifier="material" to the components when ons.platform.isAndroid() is true. You can disable this feature by running ons.disableAutoStyling() right after including onsenui.js (i.e. before the app is initialized). If you disable it you may need to manually specify modifier="material" in every component you want to display with Material Design. You can also specify disable-auto-styling attribute in specific components that you don’t want to auto style.

Some tools are provided to give a more accurate customization.

Platform utilities

ons.platform object is available with methods such as ons.platform.isIOS()ons.platform.isWebView(), etc.

You can set a platform with ons.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 including onsenui.js).

With this, for example, 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:

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

The second icon will be displayed when material modifier is present (other modifiers can be used).

CSS Definitions

Onsen UI styles are defined in onsenui.css and onsen-css-components.css. They are written in the Stylus format.

onsenui.css is a core CSS module that defines styles for the custom elements. The source code exists under core/cssdirectory. onsen-css-components.css contains CSS definitions for CSS components. The source code exists in css-components/components-src/stylus.

You can also use Onsen CSS Components to customize pre-defined colors. After the customization, you can download and replace to the existing onsenui-css-components.css to reflect the changes.

Overriding CSS style

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

For example, if you want to apply a thick border only to a specific button, you can define like the one below.

<ons-button modifier="thick">Thick Button</ons-button>

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

<style>
.button--thick {
  border: 10px;
}
</style>

相关文章