Preface
- What should we pay attention to when adding attributes in JSX and how do the child elements in JSX operate?
- The case problem of components, the use of extension operators, and how to cycle through an object
- What does prop s in JSX refer to and what should be paid attention to in the form's labe?
Although the above questions are very clear, are they always unclear? After reading this article, you will be enlightened
JSX add specific properties
Custom tags expand the capabilities that native HTML tags do not have. One of the biggest uses is attribute value passing. The attribute value of tags can be strings or variable objects
For example: as follows
const element = <div divIndex ="0"></div>
Of course, you can also use the following method, which is equivalent to wrapping variables with a brace {}
const element = <div divIndex={"0"}></div>
As for more interpolation expressions, you can see the previous section React learning (2) - JSX in depth
It's important to note here that you embed javascript expressions in properties, and don't put quotes around double braces. For example, the following is wrong
const element = <div divIndex="{ variable }"></div>
That is, for strings or expressions in double braces, you cannot use both symbols for the same property
Be careful
JSX syntax is closer to Javascript than HTML, just looks like it. For attribute names of custom components in real, camelCase hump naming is used to define attribute names. For example, class attribute className in JSX is defined, and devindex becomes divIndex
Child elements in JSX
In native HTML tags, it's easy to understand the child elements of JSX if you are familiar with DOM structure tree
The tags of native HTML are called nodes, which have node attributes and node contents
If a tag or React component has no content, you can use / > to close it, just like XML syntax, such as the following
const element = <img src={ user.avatarUrl} />
JSX tags can contain many sub elements
For example: as follows
const element = ( <div> <h1 title="I am the son. h1 Content of element attribute">I am the son. h1 Node content of element</h1> <h2>Welcome to wechat itclanCoder official account</h2> <h3>Sichuan is the most handsome young man in the whole universe</h3> </div> )
The content of the JSX expression contained between the start and end tags will be passed to the outer component as the specific property props.children
There are several different ways to pass child elements
- string literal
You can put the string between the start and end tags. props.children is just the string. It is very useful for built-in HTML elements, but at the same time, pay attention to how to receive this content
<MyComponent>itclanCoder</MyComponent>
The sub element content of JSX and mycomponent above is itclanCoder, which can be obtained through props.children. It is a string itclanCoder without transfer
JSX will remove the first and last lines and empty lines. The empty lines adjacent to the label will be deleted, and Singapore Airlines between text strings will be compressed with a space
So the following are all equivalent, but the author suggests that the new line should be the new line
<div>itclanCoder</div> <div> itclanCoder </div> <div> //Chuan Chuan itclanCoder </div> <div> itclanCoder </div>
- JSX child element nesting
In React, child elements are allowed to be composed of multiple JSX elements, and components can nest components, such as
<MyContainer> <Header /> <Navigator /> <Aside /> <Footer /> </MyContainer>
In React, different types of child elements can be mixed together, which is the same as writing HTML before
<div> It's hot in July <ul> <li>item1</li> <li>item2</li> <li>item3</li> </ul> </div>
In the React component, the return value of the return of the render function can return an array, for example
render() { // return is followed by an array return [ <div key="div1">div1</div>, <div key="div2">div2</div>, <div key='div3'>div3</div> ] } // Of course, in order to have a better look, it's better to define a variable render() { var aDiv = [ <div key="div1">div1</div>, <div key="div2">div2</div>, <div key='div3'>div3</div> ] return aDiv; }
- javascript expression as child element
In interpolation expressions, javascript expressions can be wrapped in double braces {}. The following two writing methods are equivalent, which is the same as the above mentioned
<myComponent>Chuan Chuan</myComponent> // Equivalent to <myComponent>{'Chuan Chuan'}</myComponent>
As for the practical use of this writing method: it is very useful for displaying lists of any length, rendering HTML lists
import React from 'react'; import ReactDOM from 'react-dom'; class Item extends React.Component { constructor(props) { super(props); } render() { return ( <ul> <li>{ this.props.message }</li> </ul> ); } } class TodoLIst extends React.Component { constructor(props) { super(props); this.todos = ['Get up', 'Brush one's teeth', 'Wash one's face', 'work']; } render() { return ( <div> { this.todos.map((message) => <Item key = {message} message = { message } />) } </div> ); } } const container = document.getElementById('root'); ReactDOM.render(<TodoLIst />, container);
The effect is as follows:
- Function as child element
{} interpolation expressions can be variables, strings, ordinary HTML elements, even components, and functions
import React from 'react'; import ReactDOM from 'react-dom'; function Repeat(props){ let items = []; for(let i = 0; i < props.numTimes; i++) { items.push(props.children(i)); } return <div>{ items }</div> } function ListOfTenFun() { return ( <Repeat numTimes={ 10 }> { (index) => <div key={index}>I am a list. { index }</div> } </Repeat> ) } const container = document.getElementById('root'); ReactDOM.render(<ListOfTenFun />, container);
The effect is as follows:
The above two function components are used, in which another component can be nested, and the property value can be obtained through props
It also shows that you can pass anything to a custom component as a child element. As long as the component can be converted into an object understood by React before rendering, it can be used to expand JSX
Custom components must start with an uppercase letter
Generally speaking, if the HTML tag with lowercase letter beginning in React is called a normal element, it is a built-in element of native HTML (also can be regarded as a component). For example, < div > < span > < a > will be converted by React to generate the corresponding string 'div','span 'will be passed to React.createElement as a parameter
The element with the beginning of uppercase letter, we regard it as a custom component, such as < MyButton / >, in fact, it will also be transformed by React.createElement function
It's a conventional rule to name custom components with uppercase letters. In essence, it's a constructor to distinguish ordinary functions and simulate class functions. However, class syntax is provided by Es6, which will be used more in the future
The first part of the JSX tag specifies the type of React element
Any JSX tag element that starts with an uppercase letter means that they are React components
If the initial of a component you define is lowercase, React will be treated as a common element, while the native HTML tag does not include your custom element, it will report an error
For example: as follows
import React from 'react'; import ReactDOM from 'react-dom'; // The following is the function component defined. The initial is lowercase. This is incorrect function myButton(props) { return ( <div> <button>{ props.content }</button> </div> ) } function OutButton(){ return ( <myButton content="Button" /> ); } const container = document.getElementById('root'); ReactDOM.render(<OutButton />, container); // The right way to write, capitalized, humped function MyButton(props) { return ( <div> <button>{ props.content }</button> </div> ) } ReactDOM.render(<OutButton />, container);
Although the wrong writing method will not report errors, it will regard button as an html common tag element. It will not achieve the expected effect
Be careful:
React must be in the scope. JSX is actually the syntax sugar of React.createElement function. React.createElement is closer to the underlying API, so the react library must also be included in the scope of JSX code
Part of the purpose of introducing React library is to identify JSX syntax, which is also the reason why when you define a React component, you need to introduce React library
Use dot (.) syntax
Sometimes, when it is necessary to export multiple React components in a module, it is very convenient to use point syntax to reference a React component in JSX, for example, as follows:
import React, { Fragment, Component } from 'react'; import ReactDOM from 'react-dom'; // MyButton component class MyButton extends Component { constructor(props){ super(props); } render() { return ( <Fragment> <button>{ this.props.btnContent }</button> </Fragment> ); } } // MyInput component class MyInput extends Component{ constructor(props) { super(props); } render() { return ( <Fragment> <input value = { this.props.inputValue } /> </Fragment> ); } } // Search part class SearchArea extends Component { render() { return ( <Fragment> <FormComponent.MyInput inputValue="I am input Content of component input box" /> <FormComponent.MyButton btnContent="Search button" /> </Fragment> ); } } let FormComponent = { MyButton: MyButton, MyInput: MyInput } // Or here is an equivalent of Es6 let FormComponent = { MyButton, MyInput } const container = document.getElementById('root'); ReactDOM.render(<SearchArea />, container);
The final results are as follows:
The above is a module (search) in the page, and the related components are centralized under one object for management. Of course, in the actual development, it varies from person to person. If you see someone else writing this, don't feel strange
Extension operator, attribute expansion
For the extension operator (...), it is a very useful syntax. If you already have a props object, you can use the extension operator... To pass the entire props object in JSX as follows:
function PersonA() { return ( <Info name="Chuan Chuan" age="A handsome post-90s guy in front row" /> ); } // The above return is equivalent to function personA() { const props = { name: "Chuan Chuan", age:"A handsome post-90s guy in front row"} return ( <Info { ...props } /> ); } function Info(props){ return ( <div>{ props.name }--{ props.age }</div> ); } const container = document.getElementById('root'); ReactDOM.render(<PersonA />, container);
Small tips: how to output an object?
For array objects, you can output through the map method, but if it is an object, there is no such method
Specifically, the method object.keys (object) is used. It will return an array and save the attribute name of the object in an array. If you want to get the attribute value of the object, you can first turn the array, and then use some methods of the array: for example, the map method for processing
var obj = { name: "Chuan Chuan", age: "Have a guess,A piece of fresh meat" } var getAttr = Object.keys(obj); var getValue = Object.keys(obj).map((item) => obj[item]); console.log(getAttr); // ["name", "age"] console.log(getValue);// ["Sichuan", "guess, a piece of fresh meat"]
As shown in the following real example
import React, { Fragment, Component } from 'react'; import ReactDOM from 'react-dom'; class List extends Component { constructor(props) { super(props); // To simplify the code, bind this this.content = this.props.content; this.value = this.props.value; } render() { return ( <Fragment> <ul> { <li>{ this.content }-- { this.value }</li> } </ul> </Fragment> ); } } class Person extends Component { constructor(props) { super(props); this.person = { name: "Chuan Chuan", age: "A handsome post-90s guy in front row", desc: "Welcome to wechat itclanCoder official account" } } render() { let getPerson = Object.keys(this.person); return ( <Fragment> { getPerson.map((item) => <List key = { item } content = { item } value = { this.person[item]} /> ) } </Fragment> ); } } const container = document.getElementById('root'); ReactDOM.render(<Person />, container);
The final effect is as follows:
props in JSX
The attribute defined by the custom component is called prop, and the attribute value is called prop value. Since the component can define multiple attributes, there are many ways to specify props in JSX
Because JSX will be converted to react. CreateElement (component element, attribute object, child element), for example: JSX as follows
const info = { title:"I am a component", number: 20 } // Store the info object in the infoMessage variable property and pass it to the MyComponent component <MyComponent infoMessage = { info }>my component</MyComponent> // Will eventually be converted into React.createElement(MyComponent, { infoMessage: info}, 'my component')
For how to verify the conversion of JSX to React.createElement(), you can go to the official website of babel online compilation for verification
Open the following website
The place where the component is called is called the parent component, while the place where the component is defined is called the child component. The corresponding child component wants to receive the value of the parent component and uses props to receive it
HTML for in label
In the native html tag, label and for and id in input are used together to increase the touch range of the mouse and enhance the user experience
For should be written as HTML for in JSX
<label htmlFor="firstname">First name:</label> <input type="text" name="firstname" id="firstname">
The results are as follows
epilogue
This paper mainly discusses that the naming method of adding attributes in JSX should be camelCase camel naming to define the names of attributes. The sub elements in JSX can be strings, nested, and js expressions and functions can be sub elements
And in the definition and call of the component in React, the initial of the component name must be uppercase. When exporting multiple React components, use point syntax to reference a React component
Use the expand operator... To pass the entire props object in JSX
Sometimes, it is a very useful syntax. In addition, when traversing an object to render, the object does not have some methods of array, which are converted by Object.keys(), and then used. The properties and property values of the object can be obtained
Also know what props are in JSX and how to receive props values
For the use of label and input, pay attention to some places
Of course, there are so many things to learn about JSX for the time being. Programming is an art of continuous exploration. I hope to share these things for you