Home  >  Article  >  Web Front-end  >  How to write React components? (code)

How to write React components? (code)

不言
不言Original
2018-09-11 15:40:001455browse

The content of this article is about how to write React components? (code), it has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

How to write a React component

In the world of React, a component is usually declared with class, which must inherit from React.Component.
For example, the following code:

// MyFirstComponent.jsx
class MyFirstComponent extends React.Component {
  state = {
    text: "Hello React"
  };

  /** 组件生命周期钩子函数:在组件挂载完成后立即被调用 */
  componentDidMount() {
    alert("组件挂载完成!");
  }

  render() {
    return (
      <p>{this.state.text}, I am {this.props.author}!</p>
    )
  }
}

export default MyFirstComponent;
// index.js
import MyFirstComponent from "MyFirstComponent";

/** 渲染结果:<p>Hello React, I am Shaye!</p> */
ReactDOM.render(<MyFirstComponent author="Shaye"></MyFirstComponent>, document.getElementById("app"));

The above is a conventional way of writing React components, but we can also find several interesting things by observing the above code:

    ## There is a function
  1. componentDidMount

    in #MyFirstComponent which is the component life cycle hook function. In fact, React has designed a series of life cycle hook functions for components

  2. There is a special function render() in MyFirstComponent, this The function takes template content similar to htmljsx as the return value. This is a function that must be defined, otherwise React will throw an error

  3. jsx At first glance, it looks like a template engine, It is actually a syntax extension of JavaScript. Its core concept is the famous all in js. It is completely implemented inside JavaScript. It is the same as Like traditional template engines, you can also bind jsexpressions

  4. jsxThe bound data can be clearly seen from the two Objects: this.state and this.props; this.state is the internal custom component state of MyFirstComponent; this.props is the data passed externally into MyFirstComponent in the form of label attributes, similar to the function parameters;

In summary, when Once you have mastered

Component life cycle JSX Component state state Component attribute props , you will know how to write React components.

Component life cycle

The official document has a very detailed introduction, so I won’t go into details here. Please click here to view the official document of the component life cycle.

JSX

You can freely use

javaScript expressions in JSX, in JSX## The expressions in # should be enclosed in curly brackets. For example, the following code:

<p className={this.state.clname} style={{ fontSize: "20px" }}>{this.state.content} forever</p>

The React elements in JSX

, such as p, will eventually be translated by the compiler and processed by certain specific functions. Into a lightweight javascript object. For example, the element p mentioned above will eventually become the following object: <pre class="brush:php;toolbar:false">// 注意: 以下示例是简化过的(不代表在 React 源码中是这样) const pElement = {   type: &quot;p&quot;,   props: {     // this.state.clname的值     className: &quot;love&quot;,     style: {       fontSize: &quot;20px&quot;     },     // &quot;you&quot;为this.state.content的值     children: [&quot;you&quot;, &quot;forever&quot;]   } }</pre>React operates

DOM

by reading these objects. And keep the data content consistent. So, actually you are still writing js. Therefore, class and style must be written in the same way as js. For example: class =>
classNameAnother example: font-size: 20px; =>
{ fontSize: "20px" }Specially, the attributes of the React element are still You can use quotes to define properties with string values ​​like native html

, for example:

className="my-claname"In addition to the above, # The event binding of ##JSX also has some grammatical differences from the native

html

: The event naming of React is written in camel case instead of lowercase .

  • React event binding must be a function object, not a string.

  • Code example:

    <p onClick={this.handleClick}>我是一个按钮</p>
    
    // 也可以向事件回调函数传递参数
    <p onClick={(params) => this.handleClick(params)}>我是一个按钮</p>
Component state state

state is private and fully protected Controlled by the current component. Since it is a status, there will be a need to update it. How to update it?

Code example:

// 对`this.state`或者它的属性直接`=`赋值,将永远不会触发组件渲染,必须使用`setState()`

// 在组件的生命周期钩子函数中调用this.setState()
componentDidMount() {
  this.setState({
    content: "lalalala"
  })
}

// 在组件的自定义函数中调用this.setState()
handleClick = () => {
  this.setState({
    content: "uauauaua"
  })
}
setState()
is the only way to dynamically update components in React. When it is called, the own component and all its sub-components will trigger Re-renderingIn particular,

state can also be passed to sub-components as properties;
setState()Detailed documentation
Component properties props

props is the data passed from the parent component, usually the

state

from the parent component or other member variables of the component. Moreover, props is read-only, and components can never modify their own props. Only after the parent component calls setState() can the properties of the child component be changed and re-rendered. props can only be passed from top to bottom, and components can only modify their own private state
, which means that the data flow of the entire application can only be from top to bottom. One-way data flow underSummary

Component life cycle JSX Component state state Component attribute props Plus a top-down order To data flow, these are the most basic features of React components!

Related recommendations:

How to use React high-order components

How to use this in React components

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