In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
In this article, the editor introduces in detail the "case Analysis of the use of react basic Grammar", with detailed contents, clear steps and proper handling of details. I hope that this article "case Analysis of the use of react basic Grammar" can help you solve your doubts.
1. Rendering elements (function method, es6 mode)
1. The code of the function method is as follows:
Function Clock (props) {return (Hello, world! Now it is {props.date.toLocaleTimeString ()}. );} function tick () {ReactDOM.render (, document.getElementById ('example'));} setInterval (tick, 1000)
2. The code of es6 method is as follows:
Class Clock extends React.Component {render () {return (Hello, world! Now it is {this.props.date.toLocaleTimeString ()}. );}} function tick () {ReactDOM.render (, document.getElementById ('example'));} setInterval (tick, 1000)
II. Components
1. Use the function to define the component. The code is as follows:
Function HelloMessage (props) {return Hello Worldwide;}
You can also use ES6 class to define components, as follows:
Class Welcome extends React.Component {render () {return Hello Worldwide;}}
2. If we need to pass parameters to the component, we can use the this.props object as follows:
Function HelloMessage (props) {return Hello {props.name}!;} const element =; ReactDOM.render (element, document.getElementById ('example'))
Of course, when we add attributes, the class attribute needs to be written as class Name, and for the for attribute, we need to write htmlFor. Why? Because class and for are reserved words for JavaScript, you need to do this.
3. Composite components
For composite components, we can create multiple components to form a single component, which can separate components with different functions. The code is as follows:
Function Name (props) {return name: {props.name};} function Url (props) {return address: {props.url};} function Nickname (props) {return alias: {props.nickname};} function App () {return ();} ReactDOM.render (, document.getElementById ('example'))
III. Events
When we define a component by using ES6 class syntax, the event handler becomes a method of the class. In this method, we render a button that allows the user to switch the switch state through the Toggle component, as follows:
Class Toggle extends React.Component {constructor (props) {super (props); this.state = {isToggleOn: true}; / / binding here is necessary so that `this` can use this.handleClick = this.handleClick.bind (this) in the callback function;} handleClick () {this.setState (prevState = > ({isToggleOn:! prevState.isToggleOn})) } render () {return ({this.state.isToggleOn? 'ON':' OFF'});}} ReactDOM.render (, document.getElementById ('example'))
However, we should note that the method of the class does not bind this by default. If we forget to bind this.handleClick and pass it into onClik, the value of this will be undefined when you call this function. Of course, we can also use the following two ways to solve the problem.
(1) when we use the experimental attribute initializer syntax, we can use the property initializer to bind the callback function correctly, as follows:
Class LoggingButton extends React.Component {/ / this syntax ensures that `this` is bound in handleClick / / here is just a test handleClick = () = > {console.log ('this is:', this);} render () {return (Click me);}} ReactDOM.render (, document.getElementById (' example'))
(2) if we do not use the attribute syntax, we can call back the arrow function used in the function, as follows:
Class LoggingButton extends React.Component {handleClick () {console.log ('this is:', this);} render () {/ / this syntax ensures that `this` is bound in handleClick return (this.handleClick (e)} > Click me);}}
The code for passing parameters for events is as follows:
This.deleteRow (id, e)} > Delete RowDelete Row
The above two methods are equivalent, and in our case the parameter e as the time object will be passed as the second parameter. Through the arrow function, the event object must be passed explicitly, but through the bind way, the time object and more parameters will be passed implicitly. Of course, we also need to note that parameters need to be passed to the listener function through bind. For the listener function defined in the class component, the event object e should be listed after the passed parameter. The code is as follows:
Class Popper extends React.Component {constructor () {super (); this.state = {name:'Hello worldview'};} preventPop (name, e) {/ / event object e to be placed at the end of e.preventDefault (); alert (name);} render () {return (
Hello
{/ * pass parameters through the bind () method. * /} Click);}} ReactDOM.render (, document.getElementById ('example'))
IV. Conditional rendering
When we talk about conditional rendering, we first take a look at these two components. The code is as follows:
Function UserGreeting (props) {return Welcome back!;} function GuestGreeting (props) {return please register first. ;}
Then we create a Greeting component that displays one of them based on whether the user is logged in or not, with the following code:
Function Greeting (props) {const isLoggedIn= props.isLoggedIn; if (isLoggedIn) {return;} return;} ReactDOM.render (/ / attempt to modify isLoggedIn= {true}:, document.getElementById ('example'))
5. Element variables
We can use variables to store elements. It can help you conditionally render part of the component, while the rest of the output will not be changed. In the following example, we are going to create a stateful component called LoginControl. It will render or according to the current state, and it will also render the one in the previous example. The code is as follows:
Class LoginControl extends React.Component {constructor (props) {super (props); this.handleLoginClick = this.handleLoginClick.bind (this); this.handleLogoutClick = this.handleLogoutClick.bind (this); this.state = {isLoggedIn: false};} handleLoginClick () {this.setState ({isLoggedIn: true});} handleLogoutClick () {this.setState ({isLoggedIn: false});} render () {const isLoggedIn = this.state.isLoggedIn; let button = null If (isLoggedIn) {button =;} else {button =;} return ({button});}} ReactDOM.render (, document.getElementById ('example'))
VI. With the operation
We can embed any expression in JSX by wrapping the code in curly braces, including the logic of JavaScript and & &, which can easily render an element conditionally as follows:
Function Mailbox (props) {const unreadMessages = props.unreadMessages; return (Hello! {unreadMessages.length > 0 & & you have {unreadMessages.length} unread messages. });} const messages = ['React',' Re: React', 'Re:Re: React']; ReactDOM.render (, document.getElementById (' example'))
In JavaScript, true & & expression always returns expression, while false & & expression always returns false. Therefore, if the condition is true,&&, the element to the right will be rendered, and if it is false,React, it will be ignored and skipped.
(1), ternary operator
Another method of conditional rendering is to use JavaScript's conditional operator: import code:
Render () {const isLoggedIn = this.state.isLoggedIn; return ({isLoggedIn? (): ());}
7. Block component rendering
In rare cases, you may want to hide the component, even if it is rendered by other components. Let the render method return null instead of its render result. So now let's take a look at the following example, rendering based on the value of the property warn. If the value of warn is false, the component will not render with the code as follows:
Function WarningBanner (props) {if (! props.warn) {return null;} return (warning!);} class Page extends React.Component {constructor (props) {super (props); this.state = {showWarning: true} this.handleToggleClick = this.handleToggleClick.bind (this);} handleToggleClick () {this.setState (prevState = > ({showWarning:! prevState.showWarning})) } render () {return ({this.state.showWarning? 'hide': 'show'});}} ReactDOM.render (, document.getElementById ('example'))
In the code, we can see that the return of null by the component's render method does not affect the callback of the component's lifecycle method. For example, componentWillUpdate and componentDidUpdate can still be called.
8. List
Creating a category is done through the map () method of JavaScript, as follows:
Const numbers = [1,2,3,4,5]; const listItems = numbers.map ((numbers) = > {numbers}); ReactDOM.render ({listItems}, document.getElementById ('example'))
The above instance can be reconstructed into a component in the code. The component receives array parameters and each list element is assigned a key, otherwise a warning a key should be provided for list items will appear, which means that the key needs to be included: the code is as follows:
Function NumberList (props) {const numbers = props.numbers; const listItems = numbers.map ((number) = > {number}); return ({listItems});} const numbers = [1,2,3,4,5]; ReactDOM.render (, document.getElementById ('example'))
IX. Keys
For this keys, it helps React identify which elements have changed when some elements in the DOM are added or deleted. So you should assign a definite identity to each element in the array. The code is as follows:
Const numbers = [1,2,3,4,5]; const listItems = numbers.map ((number) = > {number})
The key of an element is preferably a unique string that the element has in the list. Typically, we use the id from the data as the key of the element: the code is as follows:
Const todoItems = todos.map ((todo) = > {todo.text})
However, when the element does not have a definite id, you can use its serial number index index as the key: the code is as follows:
Const todoItems = todos.map ((todo, index) = > / / use {todo.text} only if there is no definite id)
But if the element does not have a definite id, then it can use index as the key, as follows:
Const todoItems = todos.map ((todo, index) = > / / use {todo.text} only if there is no definite id)
If the list can be reordered, it is not recommended to use an index for sorting, as this can cause rendering to become slow.
1. The key of the element should be unique among brothers.
We know that the key used in array elements should be unique among its brothers. However, they do not need to be globally unique. When we generate two different arrays, we can use the same key as follows:
Function Blog (props) {const sidebar = ({props.posts.map ((post) = > {post.title})}); const content = props.posts.map ((post) = > {post.title})
{post.content}
); return ({sidebar} {content});} const posts = [{id: 1, title: 'Hello World', content:' Welcome to learning Reactless'}, {id: 2, title: 'Installation', content:' You can install React from npm.'}]; ReactDOM.render (, document.getElementById ('example'))
Of course, key will also serve as a hint to React, but it will not be passed on to your components. If you need to use the same value as key in your component, pass it as a property:
The code is as follows:
Const content = posts.map ((post) = >)
2. Embed map () in js
Let's start by wrapping a separate listtems variable in js as follows:
Function NumberList (props) {const numbers = props.numbers; const listItems = numbers.map (number) = >); return ({listItems});}
JSX allows any expression to be embedded in curly braces, so we can use it in map () as follows:
Function NumberList (props) {const numbers = props.numbers; return ({numbers.map ((number) = >)}) } after reading this, the article "case Analysis of the use of react basic Grammar" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.