markdown 反应原生指南

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown 反应原生指南相关的知识,希望对你有一定的参考价值。

# General
As described on their website, React Native is a framework for building native apps using React.
React itself, is a Javascript library for building user interfaces. The 3 capital notions in React Native are: components, states and props.

# Components
Components are UI elements that manage their own states and props. In a React Native application, one or more components are used to compose a view.
Each component can be customized with props and state. Keep in mind that the render of a component is fully linked to props and state. It will be always the same render, with same props and states.
Also, each time of a state or a props changes, the render methods of the component and children components are called. To keep good performances, you can use the `shouldComponentUpdate(nextProps, nextState)` method to let let React know if a component’s output is not affected by the current change in state or props.

Other methods are important to know for component lifecycle management:
### Mounting
These methods are called when an instance of a component is being created and inserted into the DOM:

- constructor()
- componentWillMount()
- render()
- componentDidMount()

### Updating
An update can be caused by changes to props or state. These methods are called when a component is being re-rendered:

- componentWillReceiveProps()
- shouldComponentUpdate()
- componentWillUpdate()
- render()
- componentDidUpdate()

### Unmounting
This method is called when a component is being removed from the DOM:

- componentWillUnmount()

# Props
Props are parameters that are set by their parents when components are created. These props can then be used in the component render method.

### Props exemple
````javascript
// in the component file
class Hello extends Component {
  render() {
    return (
      <Text>Hello {this.props.name}!</Text>
    );
  }
}

// to use the component
<View>
  ...
  <Greeting name='Rexxar' />
  ...
</View>
```

# State
While props are fixed throughout the lifetime of a component, the state is used for data that is going to change.
The component is updated when the `setState()` method is called.

### Initialise the state
````javascript
class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {isShowingText: true}; //state init

    setInterval(() => {
      this.setState(previousState => {
        return { isShowingText: !previousState.isShowingText };
      });
    }, 1000);
  }

  render() {
    let display = this.state.isShowingText ? this.props.text : ' ';
    return (
      <Text>{display}</Text>
    );
  }
}
```

# Styling
React Native use stylesheets, that reminds CSS syntax.

### Exemple
````javascript

render() {
  return (
    <Text style={styles.bigblue}>Hello</Text>
  )
}

const styles = StyleSheet.create({
  bigblue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30,
  },
  red: {
    color: 'red',
  },
});
```

# Networking
React Native provides the Fetch API for your networking needs. You can additionnaly use Javascript "Promise" to handle the whole Networking exchange

### Exemple
````javascript
export const searchService = pattern => new Promise((res, rej)=>{
    fetch(`${API_URL}?term=${pattern}`)
    .then(
        resp => resp.json()
    )
    .then(
        apiData=>res(apiData)
    )
    .catch(
        err=>rej(err)
    )
})
```

### Usage
````javascript
myComponentFunction() {
 searchService(pattern)
  .then(
    apiData => this.setState({res: [...apiData.results]})
  ).catch(
    err => console.log(err)
  ) 
}
````

# Project structure
For projects with redux
````javascript
.
├── _tests // test folder
├── android // Android related folder
├── app // main application folder
│   ├── actions // all the actions used by redux
│   ├── components // all the React Native components
│   ├── constants // all const files
│   ├── middleware // middleware for all actions
│   ├── reducers // redux stuff
│   ├── scenes // all scenes of the app
│   └── services // all the networking stuff
│   └── utils // utils code shared in the app 
├── assets
│   ├── fonts
│   └── images
└── ios // iOS related folder
````

### Middleware
Used to create a queue of actions, for non-blocking treatment and order respect.

````javascript
export default (store) => (next) => (action) => {
  let syncActivityFinished = false;
  let actionQueue = [];

  function flushQueue() {
    actionQueue.forEach(a => store.dispatch(a));
    actionQueue = [];
  }

  function asyncDispatch(asyncAction) {
    actionQueue = actionQueue.concat([asyncAction]);

    if (syncActivityFinished) {
      flushQueue();
    }
  }

  const actionWithAsyncDispatch = Object.assign({}, action, {asyncDispatch});

  next(actionWithAsyncDispatch);
  syncActivityFinished = true;
  flushQueue();
};
````

All the actions are then linked with
`const store = createStore(AppReducers, applyMiddleware(AsyncDispatchMiddleware));`
 
# Tools

# Awesome
- https://github.com/jondot/awesome-react-native

# Guidelines
- https://github.com/airbnb/javascript
- https://github.com/airbnb/javascript/tree/master/react
- https://google.github.io/styleguide/jsguide.html
- https://github.com/rwaldron/idiomatic.js/
- https://github.com/standard/standard

# Guides
## Plateform specific code
### Plateform module
````javascript
import {Platform, StyleSheet} from 'react-native';

const styles = StyleSheet.create({
  containerA: {
    height: Platform.OS === 'ios' ? 200 : 100
  },
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});
````
### Detecting Android Version
````javascript
import {Platform} from 'react-native';

if (Platform.Version === 25) {
  console.log('Running on Nougat!');
}
````

### Detecting iOS Version
````javascript
import {Platform} from 'react-native';

const majorVersionIOS = parseInt(Platform.Version, 10);
if (majorVersionIOS <= 9) {
  console.log('Work around a change in behavior');
}
````

### Specific extensions
Create 2 differents files
`BigButton.ios.js`
`BigButton.android.js`

At import, it will automatically select the good version
`const BigButton = require('./BigButton');`

## Animations
- https://medium.com/react-native-training/react-native-animations-using-the-animated-api-ebe8e0669fae
- https://facebook.github.io/react-native/docs/animations.html

## Improve UX
- Configure Text inputs
  - Use placeholders
  - Auto focus first text input
  - Disable auto-correct / autocapitalization
  - Choose the right keyboard type (email, numeric...)
  - Configure return keys
- Use native components at best
- Use specific UI code to respect guidelines
- Make sure that the keyboard don't hide important elements (use KeyboardAvoidingView)
- Make tappable areas larger (hitSlop prop or padding)
- Lock screen orientation
- Give feedback on touch events (higlights, ripple...)
- Enable cancel-ability (cancel action by draging the finger away)

## Improve perf
- Make sure that you are running in development mode (dev=false)
- Only use MapsToProps props if needed
- Prefers function that return elements instead of components
- Be carefull of timers, it can cause memory leaks
- Be carefull of triggers that re-render the component (setState(), props that changes)
- Use componentShouldUpdate method to define if a component should update
- Delete all console.log()
- ListView are NOT used
- Do not do deep comparison of a large list of object in shouldComponentUpdate 
- Profile code (see: https://facebook.github.io/react-native/docs/performance.html#profiling)
- Think about unbundling and lazy require (see: https://facebook.github.io/react-native/docs/performance.html#unbundling-inline-requires)
- 

以上是关于markdown 反应原生指南的主要内容,如果未能解决你的问题,请参考以下文章

markdown 反应原生公地

markdown 反应原生项目审查清单

我们如何在反应原生项目中将多个图像合并为单个图像

反应原生弹道

使用指数反应原生的 Facebook 登录

谷歌地点选择器未打开(反应原生 ios 应用程序)