ReactNative開發入門教學(2)-觸發事件

學會寫 HelloWorld 之後,就可以來寫個簡單的APP了!

如果我們把全部的程式碼都集中在index.ios.js當中的話,會有點亂吧?

所以我看了別人寫的方法,通常都是另外放在別的地方再import進來!

所以我依樣畫葫蘆,把需要的import進來就可以了!

import React, { Component } from 'react';
import {
    AppRegistry
} from 'react-native';
import App from './src/app';

AppRegistry.registerComponent('oeapp', () => App);

所以我們在專案當中建立一個叫做 src 的資料夾,並且建立一個叫做 app.js 的

檔案,然後我們一樣先來寫個 HelloWorld 吧!

import React, { Component } from 'react';
import {
    Text,
    View,
} from 'react-native';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    render() {
        return(
            <View>
                <Text>HelloWorld!</Text>
            </View>
        );
    }
}

export default App;

執行之後應該就能看到我們寫好的HelloWorld了!

單純只執行程式實在太無聊,總是要有一些互動,所以我們來寫個按鈕並且顯示

一些什麼東西吧!

在 ReactNative 中要當作按鈕的東西除了可以使用 Button 外,也可以使用按壓

動作的 TouchableHighlight 、TouchableOpacity ,差異性可以上官網看看API!

https://facebook.github.io/react-native/docs/touchableopacity.html

這邊我就用TouchableHighlight與Button來實作!要用之前先import

import React, { Component } from 'react';
import {
    Text,
    View,
    TouchableHighlight,
    Button,
} from 'react-native';

接著修改一下 class 中的代碼

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return(
      <View>
        <Button title="Try it!" />
        <TouchableHighlight>
          <Text>HelloWorld!</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

執行之後應該會發現會出現警告,但是還是能執行。不過這些按鈕都是沒有任何作用的

因為我們得加上觸發事件才行,讓我再修改一下

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  _click() {
    alert('Clicked!');
  }
  render() {
    return(
      <View>
        <Button title="Try it!" onPress={this._click.bind(this)}/>
        <TouchableHighlight onPress={this._click.bind(this)}>
          <Text>HelloWorld!</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

在執行看看!兩個觸發事件都被指向 _click() 去了吧!這樣簡單的觸發事件就大功告成了!