Props and States

Giả sử các bạn muốn các thành phần có thể truyền dữ liệu với nhau thì cái đấy được gọi là props. Để truyền một prop vào một thành phần làm như sau:

var React = require('react');

var ReactNative = require('react-native');

var {
  AppRegistry,

  StyleSheet,

  Text,

  View,

} = ReactNative;

class HelloComponent extends React.Component {

     render () {

       return (

         <View>

           <Text>{this.props.text}</Text>

         View>
); }

}

Props có thể được truy cập ở bên trong một thành phần bằng cách this.props:

this.props.text //Ở đây tôi truy vấn đến text, phần này sẽ được làm rõ hơn ở phần dưới.

Liệu có thể truyền nhiều props vào một component được không?

Dĩ nhiên bạn có thể truyền một mảng của props vào một component khi sử dụng ES7:

<HelloComponent {...props} />

 

 

Nếu bạn muốn prop có một giá trị mặc định thì bạn có thể khai báo như sau:

HelloComponent.defaultProps = {text: "Default Text!"};

Validating props

Nếu bạn muốn component của bạn có thể truy cập ở public, mà để khi các lập trình viên khác sử dụng truyền vào các props không đúng kiểu bạn có thể valide các props đó bằng cách:

HelloComponent.propTypes = {text: React.PropTypes.string};

Phần này sẽ được sử dụng ở phần dưới validate prop của một button.

 

State

Bây giờ chúng ta đã biết cách truyền data, nhưng nếu data thay đổi thì làm thế nào để chúng ta hiển thị nó cho người dùng thấy. Vậy State là một cách tốt để biết khi nào người dung input, nó là các requests asyn vả các events. Cập nhật component bằng cách thêm đoạn sau:

class Test extends React.Component

{
  constructor (props) {

         super(props);

         this.state = {  // Set Initial State

         appendText: ''

}; }
     render () {

       return (

         <View>

           <Text onPress={() => setState({text: ' Native!'})}>{this.

   props.text + this.state.appendText}</Text>

</View> );

}

Thực hành

Tạo một Button

Bắt đầu bằng việc render ra đoạn text Simple Button ờ file mới SimpleButton.js và sau đó import class đấy vào index.ios.js như sau:

var React = require('react');

var ReactNative = require('react-native');

var {
  AppRegistry,

  StyleSheet,

  Text,

  View,

  TouchableOpacity

} = ReactNative;

   export default class SimpleButton extends React.Component {

     render () {

       return (

           <View>

             <Text> SimpleButton</Text>

         </View>

); }

}

Import SimpleButton.js vào index.ios.js:

var React = require('react');

var ReactNative = require('react-native');

var {
  AppRegistry,

  StyleSheet,

  Text,

  View,

} = ReactNative;



import SimpleButton from './SimpleButton';

class Test extends React.Component

{
  render ()

  {

    return(

      <View style={styles.container}>

          <SimpleButton/>

      </View>

    );  

  }

}

Screen sẽ như sau:

Tiếp theo sẽ thêm TouchableOpacity nó là một thành phần cũng giống như View, Text,.. vào cấu trúc trong render. TouchableHighlight, TouchableOpacity, TouchableWithoutFeedback đều có thể bắt tương tác của người dùng. Với onPress cũng giống như một thàm khi chạm vào nút thì nó sẽ thực hiện một khối lệnh nào đó. Trong ví dụ này sẽ in ra Pressed:

var React = require('react');

var ReactNative = require('react-native');

var {

  AppRegistry,

  StyleSheet,

  Text,

  View,

  TouchableOpacity

} = ReactNative;

   export default class SimpleButton extends React.Component {

     render () {

       return (

         <TouchableOpacity onPress=() => console.log('Pressed!'))>

           <View>

             <Text>{this.props.customText || 'Simple Button'}</Text>

         </View>

      </TouchableOpacity>

); }

}

Bật simulator và ấn cmd + R sau đó ấn vào Simple Button, ở xcode có thể thấy no in ra press!

Sử dụng prop khi khởi tạo Simple Button

Bây giờ chúng ta sẽ viết thêm một số đoạn mã để khi khởi tạo simple button thì nó sẽ có title, và khi onPress thì nó sẽ in ra theo string truyền vào.

var React = require('react');

var ReactNative = require('react-native');

var {

  AppRegistry,

  StyleSheet,

  Text,

  View,

  TouchableOpacity

} = ReactNative;

   export default class SimpleButton extends React.Component {

     render () {

       return (

         <TouchableOpacity onPress={this.props.onPress}>

           <View>

             <Text>{this.props.customText || 'Simple Button'}</Text>

         </View>

      </TouchableOpacity>

); }

}

SimpleButton.propTypes = {

     onPress: React.PropTypes.func.isRequired,

     customText: React.PropTypes.string

};

Sau khi chạy bạn sẽ thấy cảnh báo về việc chưa chỉ rõ prop, bạn có thể xem lại ở phần trên để hiểu cách truyền, ở file index.ios.js thay đổi như sau, với việc thay đổi này thì khi ấn vào nút nó sẽ in ra TechmasterVN, và nút có title là React

'use strict';

var React = require('react');

var ReactNative = require('react-native');

var {

  AppRegistry,

  StyleSheet,

  Text,

  View,

} = ReactNative;

import SimpleButton from './SimpleButton';

class Test extends React.Component

{

  render ()

  {

    return(

      <View style={styles.container}>

          <SimpleButton customText="React" onPress={() => console.log(Techmaster.vn!')}/>

      </View>

    );  

  }

}

const styles = StyleSheet.create({

  container: {

    flex: 1,

    justifyContent: 'center',

    alignItems: 'center',

    backgroundColor: '#F5FCFF',

  },

  welcome: {

    fontSize: 20,

    textAlign: 'center',

    margin: 10,

  },

  instructions: {

    textAlign: 'center',

    color: '#333333',

    marginBottom: 5,

  },

});

AppRegistry.registerComponent('Test', () => Test);

Tóm lại: Ở bài này chúng ta đã tìm hiểu được cách truyền dữ liệu, tạo một nút và bắt sự kiện khi ấn vào nút.