Home  >  Article  >  Web Front-end  >  How to learn React Native? Detailed explanation of the learning path of React Native

How to learn React Native? Detailed explanation of the learning path of React Native

寻∝梦
寻∝梦Original
2018-09-11 14:38:103284browse

React Native is based on React. In the process of developing React Native, knowledge of React is indispensable. Although there is an official corresponding Document, it is quite lengthy and boring to learn. Through "React Native: React Quick Learning Tutorial" you can have a more systematic and in-depth understanding of React. , everyone can read and study as needed.

Overview

This article is the first article of "React Native Quick Learning Tutorial on React". This article will explain the characteristics of React, how to use React, JSX syntax, components, and the properties and status of components.

What’s React

React is a JavaScript library for building user interfaces, allowing you to create interactive user interfaces in a simpler way.

  1. When the data changes, React will efficiently update and render the components that need to be updated. Declarative views make your code more predictable and easier to debug.

  2. Build components that encapsulate and manage their own state, and then assemble them into complex user interfaces. Since component logic is written in JavaScript rather than templates, you can easily pass rich data through your application and maintain DOM state.

  3. Learn once and write anywhere. By learning React, you can not only use it for web development, but also use React Native to develop Android and iOS applications.

is not a template but is more flexible than a template:

How to learn React Native? Detailed explanation of the learning path of React Native

Thoughts: The picture above is a screenshot of GitHub Popular’s ​​homepage, this one Pages are assembled from different components. The component-based development model allows code to be reused to a greater extent, and the assembly of components between components is very flexible.

Get Started

Before using React, you need to introduce the following js library into the page.

  • react.js

  • react-dom.js

  • browser.min.js

A total of three libraries are listed above: react.js, react-dom.js and browser.min.js, which must be loaded first. Among them, react.js is the core library of React, react-dom.js provides DOM-related functions, and browser.min.js is used to convert JSX syntax into JavaScript syntax. This step is very time-consuming. , it should be put to the server for completion.
You can download these libraries from the React official website, or you can download them locally for use.

Experience: When doing React Native development, these libraries have been initialized in the node_modules directory as the React Native core libraries, so there is no need to download them separately.

Use React

to decompress the compressed package downloaded from the above address and create a "helloworld.html" containing the following content in the root directory.

<!DOCTYPE html><html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>
    <script src="build/react.js"></script>
    <script src="build/react-dom.js"></script>
    <script src="https://npmcdn.com/babel-core@5.8.38/browser.min.js"></script>
  </head>
  <body>
    <p id="example"></p>
    <script type="text/babel">
      ReactDOM.render(
        <h1>Hello, world!</h1>,        document.getElementById(&#39;example&#39;)
      );
    </script>
  </body></html>

The code that writes XML format in JavaScript code is called JSX, which will be introduced below. To convert JSX to standard JavaScript, we use <script type="text/babel"></script> tag, and then converted by Babel into content that is actually executed in the browser.

ReactDOM.render()

ReactDOM.render is the most basic method of React, used to convert templates into HTML language and insert specified DOM nodes.

ReactDOM.render(  <h1>Hello, world!</h1>,
  document.getElementById(&#39;example&#39;)
);

上述代码的作用是将<h1>Hello, world!</h1>插入到元素id为example的容器中。

JSX

JSX 是一个看起来很像 XML 的 JavaScript 语法扩展。 每一个XML标签都会被JSX转换工具转换成纯JavaScript代码,使用JSX,组件的结构和组件之间的关系看上去更加清晰。
JSX并不是React必须使用的,但React官方建议我们使用 JSX , 因为它能定义简洁且我们熟知的包含属性的树状结构语法。

Usage:

React.render(//使用JSX    <p>
        <p>
            <p>content</p>
        </p>
    </p>,
    document.getElementById(&#39;example&#39;)
);
React.render(//不使用JSX
    React.createElement(&#39;p&#39;, null,
        React.createElement(&#39;p&#39;, null,
            React.createElement(&#39;p&#39;, null, &#39;content&#39;)
        )
    ),
    document.getElementById(&#39;example&#39;)
);

HTML标签 与 React组件 对比

React 可以渲染 HTML 标签 (strings) 或 React 组件 (classes)。 
要渲染 HTML 标签,只需在 JSX 里使用小写字母开头的标签名。

var mypElement = <p className="foo" />;
React.render(mypElement, document.body);

要渲染 React 组件,只需创建一个大写字母开头的本地变量。

var MyComponent = React.createClass({/*...*/});
var myElement = <MyComponent someProperty={true} />;
React.render(myElement, document.body);

提示:

  • React 的 JSX 里约定分别使用首字母大、小写来区分本地组件的类和 HTML 标签。

  • 由于 JSX 就是 JavaScript,一些标识符像 class 和 for 不建议作为 XML 属性名。作为替代, React DOM 使用 className 和 htmlFor 来做对应的属性。

JavaScript 表达式

属性表达式

要使用 JavaScript 表达式作为属性值,只需把这个表达式用一对大括号 ({}) 包起来,不要用引号 (“”)。

// 输入 (JSX):
var person = <Person name={window.isLoggedIn ? window.name : &#39;&#39;} />;
// 输出 (JS):
var person = React.createElement(
  Person,
  {name: window.isLoggedIn ? window.name : &#39;&#39;}
);

子节点表达式

同样地,JavaScript 表达式可用于描述子结点:

// 输入 (JSX):
var content = <Container>{window.isLoggedIn ? <Nav /> : <Login />}</Container>;
// 输出 (JS):
var content = React.createElement(
  Container,
  null,
  window.isLoggedIn ? React.createElement(Nav) : React.createElement(Login)
);

注释

JSX 里添加注释很容易;它们只是 JS 表达式而已。你只需要在一个标签的子节点内(非最外层)用 {} 包围要注释的部分。

class ReactDemo extends Component {
  render() {
    return (     
      <View style={styles.container}>
        {/*标签子节点的注释*/}        <Text style={styles.welcome}
          //textAlign=&#39;right&#39;
          textShadowColor=&#39;yellow&#39;
          /*color=&#39;red&#39;
          textShadowRadius=&#39;1&#39;*/
          >
          React Native!        </Text>
      </View>
    );
  }
}

心得:在标签节点以外注释,和通常的注释是一样的,多行用“/**/” 单行用“//”;

JSX延展属性

不要试图去修改组件的属性

不推荐做法:

  var component = <Component />;
  component.props.foo = x; // 不推荐
  component.props.bar = y; // 不推荐

这样修改组件的属性,会导致React不会对组件的属性类型(propTypes)进行的检查。从而引发一些预料之外的问题。

推荐做法:

var component = <Component foo={x} bar={y} />;

延展属性(Spread Attributes)

你可以使用 JSX 的新特性 - 延展属性:

  var props = {};
  props.foo = x;
  props.bar = y;
  var component = <Component {...props} />;

传入对象的属性会被复制到组件内。

它能被多次使用,也可以和其它属性一起用。注意顺序很重要,后面的会覆盖掉前面的。

  var props = { foo: &#39;default&#39; };
  var component = <Component {...props} foo={&#39;override&#39;} />;
  console.log(component.props.foo); // &#39;override&#39;

上文出现的… 标记被叫做延展操作符(spread operator)已经被 ES6 数组 支持。

Component

React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。

var HelloMessage = React.createClass({
  render: function() {
    return <h1>Hello {this.props.name}</h1>;
  }
});
ReactDOM.render(  <HelloMessage name="John" />,
  document.getElementById(&#39;example&#39;)
);

上面代码中,变量 HelloMessage 就是一个组件类。模板插入 <hellomessage></hellomessage> 时,会自动生成 HelloMessage 的一个实例。所有组件类都必须有自己的 render 方法,用于输出组件。

注意

  • 组件类的第一个字母必须大写。

  • 组件类只能包含一个顶层标签。

组件的属性(props)

我们可以通过this.props.xx的形式获取组件对象的属性,对象的属性可以任意定义,但要避免与JavaScript关键字冲突。

遍历对象的属性:

this.props.children会返回组件对象的所有属性。
React 提供一个工具方法 React.Children 来处理 this.props.children 。我们可以用React.Children.mapReact.Children.forEach 来遍历子节点。 
React.Children.map

array React.Children.map(object children, function fn [, object thisArg])

该方法会返回一个array。
React.Children.forEach

React.Children.forEach(object children, function fn [, object thisArg])

Usage:

var NotesList = React.createClass({
  render: function() {
    return (      <ol>
      {
        React.Children.map(this.props.children, function (child) {
          return <li>{child}</li>;
        })
      }      </ol>
    );
  }
});
ReactDOM.render(  <NotesList>
    <span>hello</span>
    <span>world</span>
  </NotesList>,
  document.body
);

PropTypes

组件的属性可以接受任意值,字符串、对象、函数等等都可以。有时,我们需要一种机制,验证别人使用组件时,提供的参数是否符合要求。
组件类的PropTypes属性,就是用来验证组件实例的属性是否符合要求。

var MyTitle = React.createClass({
  propTypes: {
    title: React.PropTypes.string.isRequired,
  },
  render: function() {
     return <h1> {this.props.title} </h1>;
   }
});

上面的Mytitle组件有一个title属性。PropTypes 告诉 React,这个 title 属性是必须的,而且它的值必须是字符串。现在,我们设置 title 属性的值是一个数值。

var data = 123;
ReactDOM.render(  <MyTitle title={data} />,
  document.body
);

这样一来,title属性就通不过验证了。控制台会显示一行错误信息。

Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`.

更多的PropTypes设置,可以查看官方文档。
此外,getDefaultProps 方法可以用来设置组件属性的默认值。

var MyTitle = React.createClass({
  getDefaultProps : function () {
    return {
      title : &#39;Hello World&#39;
    };
  },
  render: function() {
     return <h1> {this.props.title} </h1>;
   }
});
ReactDOM.render(  <MyTitle />,
  document.body
);

上面代码会输出"Hello World"

ref 属性(获取真实的DOM节点)

组件并不是真实的 DOM 节点,而是存在于内存之中的一种数据结构,叫做虚拟 DOM (virtual DOM)。只有当它插入文档以后,才会变成真实的 DOM 。根据 React 的设计,所有的 DOM 变动,都先在虚拟 DOM 上发生,然后再将实际发生变动的部分,反映在真实 DOM上,这种算法叫做 DOM diff ,它可以极大提高网页的性能表现。

但是,有时需要从组件获取真实 DOM 的节点,这时就要用到 ref 属性。

var MyComponent = React.createClass({
  handleClick: function() {
    this.refs.myTextInput.focus();
  },
  render: function() {
    return (      <p>
        <input type="text" ref="myTextInput" />
        <input type="button" value="Focus the text input" 		  onClick={this.handleClick} />
      </p>
    );
  }
});
ReactDOM.render(  <MyComponent />,
  document.getElementById(&#39;example&#39;)
);

上面代码中,组件 MyComponent 的子节点有一个文本输入框,用于获取用户的输入。这时就必须获取真实的 DOM 节点,虚拟 DOM 是拿不到用户输入的。为了做到这一点,文本输入框必须有一个 ref 属性,然后 this.refs.[refName] 就会返回这个真实的 DOM 节点。
需要注意的是,由于 this.refs.[refName] 属性获取的是真实 DOM ,所以必须等到虚拟 DOM 插入文档以后,才能使用这个属性,否则会报错。上面代码中,通过为组件指定 Click 事件的回调函数,确保了只有等到真实 DOM 发生 Click 事件之后,才会读取 this.refs.[refName] 属性。
React 组件支持很多事件,除了 Click 事件以外,还有 KeyDown 、Copy、Scroll 等,完整的事件清单请查看官方文档。(想看更多就到PHP中文网React参考手册栏目中学习)

心得:ref属性在开发中使用频率很高,使用它你可以获取到任何你想要获取的组件的对象,有个这个对象你就可以灵活地做很多事情,比如:读写对象的变量,甚至调用对象的函数。

state

上文讲到了props,因为每个组件只会根据props 渲染了自己一次,props 是不可变的。为了实现交互,可以使用组件的 state 。this.state 是组件私有的,可以通过getInitialState()方法初始化,通过调用 this.setState() 来改变它。当 state 更新之后,组件就会重新渲染自己。 
render() 方法依赖于 this.props 和 this.state ,框架会确保渲染出来的 UI 界面总是与输入( this.props 和 this.state )保持一致。

初始化state

通过getInitialState() 方法初始化state,在组件的生命周期中仅执行一次,用于设置组件的初始化 state 。

 getInitialState:function(){
    return {favorite:false};
  }

更新 state

通过this.setState()方法来更新state,调用该方法后,React会重新渲染相关的UI。
this.setState({favorite:!this.state.favorite});

Usage:

var FavoriteButton=React.createClass({
  getInitialState:function(){
    return {favorite:false};
  },
  handleClick:function(event){
    this.setState({favorite:!this.state.favorite});
  },
  render:function(){
    var text=this.state.favorite? &#39;favorite&#39;:&#39;un favorite&#39;;
    return (      <p type=&#39;button&#39; onClick={this.handleClick}>
        You {text} this. Click to toggle.      </p>
    );
  }
});

上面代码是一个 FavoriteButton 组件,它的 getInitialState 方法用于定义初始状态,也就是一个对象,这个对象可以通过 this.state 属性读取。当用户点击组件,导致状态变化,this.setState 方法就修改状态值,每次修改以后,自动调用 this.render 方法,再次渲染组件。

Experience: Since both this.props and this.state are used to describe the characteristics of components, confusion may occur. A simple way to distinguish is that this.props represents properties that, once defined, never change, while this.state is properties that change as the user interacts.

This article ends here (if you want to see more, go to the React User Manual column of the PHP Chinese website to learn). If you have any questions, you can leave a message below.

The above is the detailed content of How to learn React Native? Detailed explanation of the learning path of React Native. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn