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;
// index.js import MyFirstComponent from "MyFirstComponent"; /** 渲染结果:Hello React, I am Shaye!
*/ ReactDOM.render(, 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 functionrender()
in MyFirstComponent, this The function takes template content similar to
htmljsx
as the return value. This is a function that must be defined, otherwise
Reactwill throw an error
jsxAt 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.stateand
this.props;
this.stateis the internal custom component state of
MyFirstComponent;
this.propsis the data passed externally into
MyFirstComponentin the form of label attributes, similar to the function parameters;
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 usejavaScriptexpressions in
JSX, in
JSX## The expressions in # should be enclosed in curly brackets.For example, the following code:
{this.state.content} forever
, such asp
, will eventually be translated by the compiler and processed by certain specific functions. Into a lightweightjavascript object
. For example, the elementp
mentioned above will eventually become the followingobject
:
React operates// 注意: 以下示例是简化过的(不代表在 React 源码中是这样) const pElement = { type: "p", props: { // this.state.clname的值 className: "love", style: { fontSize: "20px" }, // "you"为this.state.content的值 children: ["you", "forever"] } }
by reading these objects. And keep the data content consistent. So, actually you are still writingjs
. Therefore,class
andstyle
must 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 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:
我是一个按钮
// 也可以向事件回调函数传递参数this.handleClick(params)}>我是一个按钮
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" }) }
setState()
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
statefrom 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.
propscan 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 befrom top to bottom. One-way data flow under
Summary
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!