How to write React components? (code)

不言
Release: 2018-09-11 15:40:00
Original
1369 people have browsed it

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 withclass, which must inherit fromReact.Component.
For example, the following code:

// MyFirstComponent.jsx class MyFirstComponent extends React.Component { state = { text: "Hello React" }; /** 组件生命周期钩子函数:在组件挂载完成后立即被调用 */ componentDidMount() { alert("组件挂载完成!"); } render() { return ( 

{this.state.text}, I am {this.props.author}!

) } } export default MyFirstComponent;
Copy after login
// index.js import MyFirstComponent from "MyFirstComponent"; /** 渲染结果:

Hello React, I am Shaye!

*/ ReactDOM.render(, document.getElementById("app"));
Copy after login

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#MyFirstComponentwhich 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 functionrender()in MyFirstComponent, this The function takes template content similar tohtmljsxas the return value. This is a function that must be defined, otherwiseReactwill throw an error

  3. jsxAt first glance, it looks like a template engine, It is actually a syntax extension ofJavaScript. Its core concept is the famousall in js. It is completely implemented insideJavaScript. It is the same as Like traditional template engines, you can also bindjsexpressions

  4. jsxThe bound data can be clearly seen from the two Objects:this.stateandthis.props;this.stateis the internal custom component state ofMyFirstComponent;this.propsis the data passed externally intoMyFirstComponentin the form of label attributes, similar to the function parameters;

In summary, when Once you have mastered

Component life cycleJSXComponent state stateComponent 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

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

{this.state.content} forever

Copy after login

The React elements in JSX

, such asp, will eventually be translated by the compiler and processed by certain specific functions. Into a lightweightjavascript object. For example, the elementpmentioned above will eventually become the followingobject:

// 注意: 以下示例是简化过的(不代表在 React 源码中是这样) const pElement = { type: "p", props: { // this.state.clname的值 className: "love", style: { fontSize: "20px" }, // "you"为this.state.content的值 children: ["you", "forever"] } }
Copy after login
React operates

DOM

by reading these objects. And keep the data content consistent. So, actually you are still writingjs. Therefore,classandstylemust be written in the same way asjs. 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 nativehtml

, for example:

className="my-claname"In addition to the above, # The event binding of ##JSXalso 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:

    我是一个按钮

    // 也可以向事件回调函数传递参数

    this.handleClick(params)}>我是一个按钮

    Copy after login
Component state state

stateis 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" }) }
Copy after login
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,

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

propsis the data passed from the parent component, usually the

state

from the parent component or other member variables of the component. Moreover,propsis read-only, and components can never modify their ownprops. Only after the parent component callssetState()can the properties of the child component be changed and re-rendered.propscan only be passed from top to bottom, and components can only modify their own privatestate
, which means that the data flow of the entire application can only befrom top to bottom. One-way data flow underSummary

Component life cycleJSXComponent state stateComponent attribute propsPlus atop-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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!