Here comes the introduction on how to build components using react-native. Even though I have done some research on react, I meet a lot problems on building my first component for a simple app.
This is the result of 2 days part time job. It’s ugly because I nearly add stylesheets to it. I won’t tell you that this is just a mixture of <Text> and my own <Select> component.
I will mainly talk about the architecture of a react-native component.
This is a simple component, I will use it to explain how to build a component.
Part 1: Import part
We need to import at least two kinds of lib here. One is the basic component provided by react and react-native, the other is the component written by ourselves.
This 1st line is required by every component, no matter react or react native, because we need to extend react Component to generate our own ones.
The 2nd part is to import components provided by react native, when we use a new react-native component, remember to import it here.( Actually I always forget it.)
The 3rd part is to import our own components, looks like the name doesn’t need to be equal to your export name( See part 4).
Part 2 : Main Class
- react class should inherit ( extend) from Component, this will provide it default functions.
- the most important method is ‘render’, it will return the body of pages. Pay attention to the grammar！
- function constructor
1) It’s the constructor method of class, remember to call super() function at first.
2) If we have state variable, remember to give init value in constructor, otherwise we will get an error.
3) If we define some new method, remember to bind it in constructor, because react didn’t provide auto binding(in class) to us.
this.showPopover = this.showPopover.bind(this);
- function getInitialState and componentDidMount are methods provided by react nativegetInitialState : Invoked once before the component is mounted. The return value will be used as the initial value of
componentDidMount : Invoked once, only on the client (not on the server), immediately after the initial rendering occurs.
Part 3: Stylesheet
As mentioned before, react native provide Stylesheet for us to add styles( css ) to our page, basically all the grammar is the same as css. We can use it like
Part 4 : Export
- export default Header;
- module.exports = Header;