Home  >  Article  >  Web Front-end  >  How to write components in React

How to write components in React

一个新手
一个新手Original
2017-10-24 11:00:132013browse

Summary of content

  • Element & Component

  • Functional & Class definition

  • Presentational & Container

  • Stateful & Stateless ComponentsStateful & Stateless

  • Controlled vs. Uncontrolled Controlled ComponentControlled & Uncontrolled

  • ##Composition & Inheritance

Element & Component

Element

Element is the smallest unit for building React applications. What the element describes is what you can see in the browser. According to what we talked about in the previous lesson, we generally use JSX to describe React elements when writing React code.

In terms of function, we can understand React elements as DOM elements; but in fact, React elements are just ordinary objects in JS. React internally implements a set of things called React DOM, or we call it Virtual DOM, which is virtual DOM. The DOM tree is simulated through a tree-structured JS object.

Speaking of which, we can talk a little bit about why React has this layer of virtual DOM? As we mentioned in the course introduction, React is fast and light. The reason why it is fast is because of the existence of this set of virtual DOM. React also implements a low-complexity and high-efficiency Diff algorithm internally, which is different from previous frameworks, such as the dirty check used by Angular. After the application data changes, React will try its best to compare as little as possible, and then only change the parts of the real DOM that need to be changed based on the virtual DOM. React also uses this to achieve its high efficiency and high performance.

Of course this is not the only meaning of virtual DOM. This layer of separate abstract logic gives React unlimited possibilities. For example, the implementation of react native allows you to master only the knowledge of JS and also apply it to other fields. Develop applications on the platform system, not just write web pages, or even other implementations such as React VR or React Internet of Things that will appear in the future.

Having said that, elements are the smallest units in React DOM that describe the UI interface. As we just mentioned, elements are actually ordinary JS objects. However, it may be difficult to understand when we use JSX to describe React elements. In fact, we can also describe it without using JSX:

const element = <h1>Hello, world</h1>;
// 用JSX描述就相当于是调用React的方法创建了一个对象
const element = React.createElement(&#39;h1&#39;, null, &#39;Hello, world&#39;);

Component

It should be noted that , Elements and components are two different concepts in React. The reason why I have talked so much before is that I am worried that everyone will accidentally confuse these two concepts. First of all, we need to make it clear that components are built on elements.

React’s official definition of components refers to independent modules that can be independently divided, reusable, and independent in the UI interface. In fact, it is similar to the definition of function in JS. It generally receives an input named props, then returns the corresponding React element, then passes it to ReactDOM, and finally renders it on the screen.

Function definition and class definition components Functional & Class

The new version of React provides two methods of defining components. Of course, the previous React.createClass can also continue to be used, but we will not include it in the scope of our discussion here.

The first function definition component is very simple. We only need to define a method that receives the props value and returns the React element:

function Title(props) {
  return <h1>Hello, {props.name}</h1>;
}

Even after using the ES6 arrow function abbreviation It can become like this:

const Title = props => <h1>Hello, {props.name}</h1>

The second type is the class definition component, which is to use the concept of classes newly introduced in ES6 to define React components:

class Title extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

After that, according to what we said above As I learned in a class, after components are defined, they can be referenced through JSX description, and components can also be nested and combined with each other.

Presentational & Container

Next we will also introduce some more in-depth concepts about components. It may sound abstract and boring now, but the following ones will be introduced This concept will be applied in subsequent courses. Students can also come back and listen to it after studying the subsequent courses according to their actual situation. I believe it will definitely help you understand React. .

The first is the most important set of concepts: display components and container components. Similarly, as we mentioned in the course introduction, React is not a traditional MVVM framework. It only works on the V layer and the view layer. Students should all know something about MVVM or MVC. So since our framework now only has the V layer, how should we deal with the relationship between data and views in actual development?

In order to solve the problem that React only has V layer and better distinguish our code logic, the concepts of display components and container components were introduced. This is also our best practice when developing React applications.

Let’s first look at a specific example to explain these two concepts:

class CommentList extends React.Component {
  constructor(props) {
    super(props)
    this.state = { comments: [] }
  }
  
  componentDidMount() {
    $.ajax({
      url: "/my-comments.json",
      dataType: &#39;json&#39;,
      success: function(comments) {
        this.setState({comments: comments})
      }.bind(this)
    })
  }
  
  renderComment({body, author}) {
    return <li>{body}—{author}</li>
  }

  render() {
    return <ul> {this.state.comments.map(this.renderComment)} </ul>
  }
  
}

这是一个回复列表组件,乍看上去很正常也很合理。但实际上在开发React应用时,我们应该避免写出这样的组件,因为这类组件担负的功能太多了。它只是一个单一的组件,但需要同时负责初始化state,通过ajax获取服务器数据,渲染列表内容,在实际应用中,可能还会有更多的功能依赖。这样,在后续维护的时候,不管是我们要修改服务器数据交互还是列表样式内容,都需要去修改同一个组件,逻辑严重耦合,多个功能在同一个组件中维护也不利于团队协作。

通过应用展示组件与容器组件的概念,我们可以把上述的单一组件重构为一个展示回复列表组件和回复列表容器:

// 展示组件

class CommentList extends React.Component {
  constructor(props) {
    super(props);
  }

  renderComment({body, author}) {
    return <li>{body}—{author}</li>;
  }
  
  render() { 
    return <ul> {this.props.comments.map(this.renderComment)} </ul>;
  } 
  
}

// 容器组件

class CommentListContainer extends React.Component {
  constructor() {
    super()
    this.state = { comments: [] }
  }
  
  componentDidMount() {
    $.ajax({
      url: "/my-comments.json",
      dataType: &#39;json&#39;,
      success: function(comments) {
        this.setState({comments: comments})
      }.bind(this)
    })
  }
  
  render() {
    return <CommentList comments={this.state.comments} />
  }
}

像这样回复列表如何展示与如何获取回复数据的逻辑就被分离到两个组件当中了。我们再来明确一下展示组件和容器组件的概念:

展示组件

  • 主要负责组件内容如何展示

  • 从props接收父组件传递来的数据

  • 大多数情况可以通过函数定义组件声明

容器组件

  • 主要关注组件数据如何交互

  • 拥有自身的state,从服务器获取数据,或与redux等其他数据处理模块协作

  • 需要通过类定义组件声明,并包含生命周期函数和其他附加方法

那么这样写具体有什么好处呢?

  • 解耦了界面和数据的逻辑

  • 更好的可复用性,比如同一个回复列表展示组件可以套用不同数据源的容器组件

  • 利于团队协作,一个人负责界面结构,一个人负责数据交互

有状态与无状态组件 Stateful & Stateless

有状态组件

意思是这个组件能够获取储存改变应用或组件本身的状态数据,在React当中也就是state,一些比较明显的特征是我们可以在这样的组件当中看到对this.state的初始化,或this.setState方法的调用等等。

无状态组件

这样的组件一般只接收来自其他组件的数据。一般这样的组件中只能看到对this.props的调用,通常可以用函数定义组件的方式声明。它本身不会掌握应用的状态数据,即使触发事件,也是通过事件处理函数传递到其他有状态组件当中再对state进行操作。

我们还是来看具体的例子比较能清楚地说明问题,与此同时,我们已经介绍了三组概念,为了防止混淆,我这里特意使用了两个展示组件来做示例,其中一个是有状态组件,另一个是无状态组件,也是为了证明,并不是所有的展示组件都是无状态组件,所有的容器组件都是有状态组件。再次强调一下,这是两组不同的概念,以及对组件不同角度的划分方式。

//Stateful Component
class StatefulLink extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      active: false
    }
  }
  handleClick() {
    this.setState({
      active: !this.state.active
    })
  }
  render() {
    return <a 
          style={{ color: this.state.active ? &#39;red&#39; : &#39;black&#39; }}
          onClick={this.handleClick.bind(this)}
         >
           Stateful Link
         </a>
  }
}

// Stateless Component
class StatelessLink extends React.Component {
  constructor(props) {
    super(props)
  }
  handleClick() {
    this.props.handleClick(this.props.router)
  }
  render() {
    const active = this.props.activeRouter === this.props.router
    return (
        <li>
            <a 
              style={{ color: active ? &#39;red&#39; : &#39;black&#39; }}
              onClick={this.handleClick.bind(this)}
             >
                Stateless Link
            </a>
    </li>
    )
  }
}

class Nav extends React.Component {
  constructor() {
    super()
    this.state={activeRouter: &#39;home&#39;}
  }
  handleSwitch(router) {
    this.setState({activeRouter: router})
  }
  render() {
    return (
    <ul>
        <StatelessLink activeRouter={this.state.activeRouter} router=&#39;home&#39; handleClick={this.handleSwitch.bind(this)} />
        <StatelessLink activeRouter={this.state.activeRouter} router=&#39;blog&#39; handleClick={this.handleSwitch.bind(this)} />
        <StatelessLink activeRouter={this.state.activeRouter} router=&#39;about&#39; handleClick={this.handleSwitch.bind(this)} />
    </ul>
    )
  }
}

上述的例子可能稍有些复杂,事实上,在React的实际开发当中,我们编写的组件大部分都是无状态组件。毕竟React的主要作用是编写用户界面。再加上ES6的新特性,绝大多数的无状态组件都可以通过箭头函数简写成类似下面这样:

/* function SimpleButton(props) {
  return <button>{props.text}</button>
} */

const SimpleButton = props => <button>{props.text}</button>

受控与非受控组件 Controlled & Uncontrolled

受控组件

一般涉及到表单元素时我们才会使用这种分类方法,在后面一节课程表单及事件处理中我们还会再次谈论到这个话题。受控组件的值由props或state传入,用户在元素上交互或输入内容会引起应用state的改变。在state改变之后重新渲染组件,我们才能在页面中看到元素中值的变化,假如组件没有绑定事件处理函数改变state,用户的输入是不会起到任何效果的,这也就是“受控”的含义所在。

非受控组件

类似于传统的DOM表单控件,用户输入不会直接引起应用state的变化,我们也不会直接为非受控组件传入值。想要获取非受控组件,我们需要使用一个特殊的ref属性,同样也可以使用defaultValue属性来为其指定一次性的默认值。

我们还是来看具体的例子:

class ControlledInput extends React.Component {
  constructor() {
    super()
    this.state = {value: &#39;Please type here...&#39;}
  }

  handleChange(event) {
    console.log(&#39;Controlled change:&#39;,event.target.value)
    this.setState({value: event.target.value})
  }

  render() {
    return (
      <label>
        Controlled Component:
        <input type="text"
               value={this.state.value}
               onChange={(e) => this.handleChange(e)}
        />
      </label>
    );
  }
}

class UncontrolledInput extends React.Component {
  constructor() {
    super();
  }

  handleChange() {
    console.log(&#39;Uncontrolled change:&#39;,this.input.value);
  }

  render() {
    return (
        <label>
          Uncontrolled Component:
          <input type="text"
                 defaultValue=&#39;Please type here...&#39;
                 ref={(input) => this.input = input}
                 onChange={() =>this.handleChange()}
          />
        </label>
    );
  }
}

通常情况下,React当中所有的表单控件都需要是受控组件。但正如我们对受控组件的定义,想让受控组件正常工作,每一个受控组件我们都需要为其编写事件处理函数,有的时候确实会很烦人,比方说一个注册表单你需要写出所有验证姓名电话邮箱验证码的逻辑,当然也有一些小技巧可以让同一个事件处理函数应用在多个表单组件上,但生产开发中并没有多大实际意义。更有可能我们是在对已有的项目进行重构,除了React之外还有一些别的库需要和表单交互,这时候使用非受控组件可能会更方便一些。

组合与继承 Composition & Inheritance

前面我们已经提到了,React当中的组件是通过嵌套或组合的方式实现组件代码复用的。通过props传值和组合使用组件几乎可以满足所有场景下的需求。这样也更符合组件化的理念,就好像使用互相嵌套的DOM元素一样使用React的组件,并不需要引入继承的概念。

当然也不是说我们的代码不能这么写,来看下面这个例子:

// Inheritance
class InheritedButton extends React.Component {
  constructor() {
    super()
    this.state = {
      color: &#39;red&#39;
    }
  }
  render() {
    return (
    <button style={{backgroundColor: this.state.color}} class=&#39;react-button&#39;>Inherited Button</button>
    )
  }
}

class BlueButton extends InheritedButton {
  constructor() {
    super()
    this.state = {
      color: &#39;#0078e7&#39;
    }
  }
}

// Composition
const CompositedButton = props => <button style={{backgroundColor:props.color}}>Composited Button</button>

const YellowButton = () => <CompositedButton color=&#39;#ffeb3b&#39; />

但继承的写法并不符合React的理念。在React当中props其实是非常强大的,props几乎可以传入任何东西,变量、函数、甚至是组件本身:

function SplitPane(props) {
  return (
    <p className="SplitPane">
      <p className="SplitPane-left">
        {props.left}
      </p>
      <p className="SplitPane-right">
        {props.right}
      </p>
    </p>
  );
}

function App() {
  return (
    <SplitPane
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}


The above is the detailed content of How to write components in React. 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