Onsen UI QUICK START FOR REACT
2016-11-17 17:50
260 查看
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:
Onsen UI for React Extension (GitHub)
You can load with a normalThe
Onsen UI not only provides custom elements, it also exposes an object called Importing
Simply use ES6 imports:
Ionicons - Prefix
Material Icons - Prefix
In general, Ionicons are good for iOS apps while the Material Icons work best for apps using Material Design.
onsenuiand
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.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> <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
onsenuiand
react-onsenuipackages, in addition to
reactand
react-domnpm packages. In the example below
onscontains Onsen UI core instance, and
Onscontains 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-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>This example is loading the following JS libraries,
<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>
react.js,
react-dom.js,
onsenui.jsand
react-onsenui.js. For stylesheets, it is loading
onsenui.cssand
onsen-css-components.csswhich 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
appid. 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/babeltype. 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
onClickprop is used to call the
handleClickmethod 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.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 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 (
left,
center, 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 theonClickprop, or text input change with the
onChangeprop.
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 onswith a lot of useful functions attached to it. The
onsobject 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.platform,
ons.notificationand
ons.orientationfor 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:
checkbox,
radio,
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,
list__item__thumbnail,
list__item__titleand
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 repeatFor 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<Carousel>and
<CarouselItem>components provide a simple carousel that can optionally be overscrollable and fullscreen.Pull-hookA 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.IconsOnsen UI bundles three icon packs to be used with
<Icon>component:Font Awesome - Prefix
fa-
Ionicons - Prefix
ion-
Material Icons - Prefix
md-
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 inons.GestureDetectorobject.
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.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.
Navigator
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.
Menu
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 manipulate
modifierattribute 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 appliesmodifier="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-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 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
materialmodifier is present (other modifiers can be used).
CSS Definitions
Onsen UI styles are defined inonsenui.cssand
onsen-css-components.css. They are written in the Stylus format.
onsenui.cssis a core CSS module that defines styles for the custom elements. The source code exists under
core/cssdirectory.
onsen-css-components.csscontains 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.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.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>
相关文章推荐
- Onsen UI for React文档
- OpenSSH for Windows: Quick Start Guide
- Lsof Readme and Quick Start for Lsof(1,2,3)
- Quick start for Microsoft MVC3 with Razor View Engine
- Maya 7 for Windows and Macintosh : Visual QuickStart Guide
- Quick Start Guide for Apache Hawq[作者:盛想]
- Robolectric_Quick Start for Eclipse
- iPhoto 6 for Mac OS X (Visual QuickStart Guide)
- (头条)Cordova+React+OnsenUI+Redux新闻App开发实战教程
- 【原】react-native start EACCESS error for setup_env.sh
- 04、Quick Start for Windows
- T4 Templates: A Quick-Start Guide for ASP.NET MVC Developers
- Quickstart for Python/WSGI applications
- C and C Complier Quickstart for Unix
- There is an internal error in the React performance measurement code.Did not expect componentDidMount timer to start while render timer is still in progress for another instance
- Rai StudiesQuick Start Site for JAVA Developers
- Quick Start Guide for Z-Wave
- 02、Quick Start for Windows phone
- .Net Quick start for the OpenFlashChart control