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:
in #MyFirstComponent
which is the component life cycle hook function. In fact, React has designed a series of life cycle hook functions for components
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
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
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;
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 usejavaScript 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>
, 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
: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">// 注意: 以下示例是简化过的(不代表在 React 源码中是这样)
const pElement = {
type: "p",
props: {
// this.state.clname的值
className: "love",
style: {
fontSize: "20px"
},
// "you"为this.state.content的值
children: ["you", "forever"]
}
}</pre><div class="contentsignin">Copy after login</div></div>
React operates
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
className="my-claname"In addition to the above, # The event binding of ##JSX
also has some grammatical differences from the native
: 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>
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()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 under
Summary
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!