1.Expanding Cards
The effect is as follows:
- The source code
- Online sample
What did you learn?
- React is the function component used to establish data communication
useState
Methods. It is used in the manner of array deconstruction, as follows:
const [state,setState] = React.useState(false);// The arguments to the useState method can be any JavaScript data type
Copy the code
The first argument to the deconstruction is the data state we define and access, and the second argument is the method we call when we need to change the data state, acting like this.setState in the class component.
Refer to the documentation useState API for more details.
2. A hook function similar to a class component, or can also be understood as a function component lifecycle useEffect. It takes a side effect function as an argument, as follows:
useEffect(() = > {});// The arrow function inside is the side effect function
Copy the code
The above example just does a simple change of document title. In fact, we can do a lot of things with this side effect function. Refer to the documentation useEffect API for details.
React has its own set of event mechanisms, which we call composite events. It is similar to a normal JavaScript binding event, but it names the event in a camel’s back, and it also wraps the event object with the name SyntheticEvent. Note that this is a cross-browser wrapper, and if we want to use nativeEvent objects, we can use the nativeEvent property, which may be covered in a later example. For example, with our event binding above:
onClick={ onChangeHandler.bind(this,index) }
Copy the code
Note here that we normally need to call bind to bind this to the component instance. The reason we bind this is because the bind event callback (as in this case :onChangeHandler) acts as an intermediate variable, The this reference is lost when the callback is called, so you need to display the this binding, which is restricted by JavaScript itself. See the reasons why React binds this for details. Similarly, to bind the composite event in the class component, we also need to display the binding this pointer.
4. Principle of map method. The map method iterates over an array, then processes the item based on the returned value, and returns the processed array. Note that this method does not alter the original array. Such as:
[1.2.3].map(i= > i <= 1);/ / return [1]
Copy the code
JSX makes use of this feature of the map method to render the list, and we need to note that a key must be specified when rendering the list, so that the DIFF algorithm can better compare the virtual DOM.
5.React adds the class name to the tag. We write it as className because class is used as a keyword in JavaScript. If we need to bind the class name dynamically, you can see that we’re using template strings, which is more like writing JavaScript, for example we can use ternary expressions to make judgments.
In React, we bind dynamic data with {} curly braces. Then we declare the style as an object. For example:
{
background:"#fff"
}
Copy the code
This means that it is a style object, and React internally converts the style object to a style string, which is then added to the DOM’s style object.
2.Progress Steps
The effect is as follows:
- The source code
- Online sample
What did you learn?
Similar to what we used in the first example, there is no need to explain. Now let’s look at something different.
- The parent component passes data to the child component, which we usually use
props
. As you can see from the example above, we exposed four props, namely:
width
stepItems
currentActive
onClickItem
Copy the code
Width is set to the container width of the step bar, which is nothing to say,stepItems is a child of the step bar, which is an array, you can also write JSX in the array item. CurrentActive is what is the current step that is passed in, it’s an index value, usually it’s a number. OnClickItem is the method that the child exposes to the parent.
- The life cycle of a class component. In this class component, we use it
constructor,componentDidMount,render
The lifecycle hook function of. We can infer from semantics that the sequence of hook functions in the lifecycle that a class component undergoes when it is initialized must beconstructor => render => componentDidMount
. Semanticallyconstructor
Is a constructor that initializes the state, and then once the initialization is complete, we render the component, and then we are ready to mount the component.
As an added bonus, we can extend the documentation so that we know the detailed life cycle. The React component lifecycle consists of three phases:
Mount => Update => Uninstall
Before the component is mounted:
Constructor => Static getDerivedStateFromProps => Render => componentWillMount => componentDidMountCopy the code
After the component state change, that is, after the update, the following is executed:
static getDerivedStateFromProps => shouldComponentUpdate => render => getSnapshotBeforeUpdate => ComponentWillReceiveProps (is out of date) = > componentWillUpdate (is out of date) = > componentDidUpdateCopy the code
After the component is uninstalled, it executes:
componentWillUnmount
Copy the code
There is also the error-handling lifecycle, which is the hook function that is executed when an error occurs during the rendering process, the lifecycle, or the constructor of a child component:
static getDerivedFromStateError => componentDidCatch
Copy the code
Some of the life cycles we haven’t used, and some of them cover almost all of our subsequent examples, so it’s important to keep in mind the order of component life cycles.
But for this example, we should learn how to encapsulate a component.
3.Rotating Navigation Animation
The effect is as follows:
- The source code
- Online sample
What did you learn?
Some of the same as the previous example of the same knowledge points needless to say, let’s look at the different knowledge points.
1. Export the module combination
//components directory index.js file
export { default as Content } from './Content';
export { default as LeftMenu } from './LeftMenu';
export { default as NavList } from "./NavList";
Copy the code
As you can see, we can export the component as above, and then we can import a separate JS file, which can be used by importing related components. As follows:
import { Content, NavList, LeftMenu } from './components/index';
Copy the code
2. How does the React component render HTML strings
React provides a dangerouslySetInnerHTML property. The value of this property is an HTML string object with __html as the property. Then we can render the HTML string as a real DOM element. As follows:
<p dangerouslySetInnerHTML={{ __html: Test code }}></p>
//
Copy the code
4.hidden-search-widget
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example is the same as the previous examples have the same knowledge points, the relevant will not be explained, will only do different knowledge points, the same subsequent.
1. Determine the data type. Using the toString method on the object prototype chain, we can get a string value of the same format as object Object, that is, we can use the string value to determine the type of data. Such as:
const getType = v= > Object.prototype.toString.call(v).slice(8, -1).toLowerCase();
const isArray = v= > getType(v) === "array";
isArray([1.2.3]);//true
isArray("");//false
Copy the code
Here, we should know the Object. The prototype. ToString. Call (v) return is similar to [Object Object] such values. So we get the second value Object by intercepting the starting index to 8 and the ending index to the string length minus 1, which is -1 in this case, and then we call toLowerCase() to convert all letters toLowerCase, and then we know the data type. For example, if the value is array, you just need to check whether the value is “array”.
2.React.createRef API
Sometimes you just need to manipulate apis for native DOM elements, such as the focus events of the input box in this example. This is where the API comes in. We can use the API to create a bridge to the DOM element and access the corresponding DOM element by accessing the current attribute of the INSTANCE of the API.
See the documentation createRef API for more details.
3. How to wrap an Input component.
This example also teaches us how to wrap an input component.
5.Blurry Loading
The effect is as follows:
- The source code
- Online sample
What did you learn?
-
Create timers in the componentDidMount life cycle and clear timers in componentWillUnmount.
-
The this.setState update state in the class component. This method takes two arguments. The first argument is our React state, which can be a function or an object. The second argument is a callback function. At this point, the question may come up: is setState asynchronous or synchronous? Here are the answers:
A: setState in React is “asynchronous” in synthesized events and hook functions, whereas it is synchronous in native events and setTimeout.
The reason why react is “asynchronous” doesn’t mean that the code inside react is “asynchronous”; in fact, it’s still a process that executes synchronously.
However, the order of the synthesis event and hook function calls precedes the update, so the updated values are not immediately available in the synthesis and hook functions, thus forming the so-called “asynchronous”.
In fact, we can retrieve the updated value by specifying the second parameter, callback.
The react.js source implementation of setState is also less complicated, adding the parameters passed as values to a defined queue (enqueueSetState) of the updater.
Bulk update optimizations in React are also based on synthesized events and hook functions (aka “asynchronous “), while bulk updates are not done in native events and setTimeout.
For example, if multiple sets of states are applied to the same value in “asynchronous” mode, they are overwritten by the policy based on the batch update, whereas if multiple sets of values are applied by the batch update policy, they are combined and then updated in batches.
Refer to the setState documentation for more details.
In addition, there is a very important utility function (which is also mentioned in the JS implementation), as follows:
const scale = (n,inMin,inMax,outerMin,outerMax) = > (n - inMin) * (outerMax - outerMin) / (inMax - inMin) + outerMin;
Copy the code
The utility function maps one range number to another. For example, map a number range from 1 to 100 to 0 to 1. For details.
6.Scroll Animation
The effect is as follows:
- The source code
- Online sample
What did you learn?
1. Dynamic components
We pass a value through props to determine the component name. Here, the Title component is used as an example, as follows:
import React from "react";
const TitleComponent = (props) = > {
let TagName = `h${ props.level }`;
return (
<React.Fragment>
<TagName>{ props.children }</TagName>
</React.Fragment>)}export default TitleComponent;
Copy the code
While the core code is fairly simple, note that the React component needs to start with a capital letter, which is a convention rule. Secondly, we pass a level through props to determine whether we are using h1 to H6 for tags. In fact, we should limit the level to 1 to 6.
2. The fragments elements
The React component needs to provide a root node, but sometimes we don’t need an actual element to wrap them as the root node, so we can use the Fragment element to wrap them. There is also a shorthand for this element <>, which is actually restricted in vue 2.x, which is restricted by the virtual DOM DIFF algorithm.
More details can be found in the document Fragment.
3. Function anti-shake
export const throttle = (fn, time = 1000) = > {
let done = false;
return (. args) = > {
if(! done) { fn.call(this. args); done =true;
}
setTimeout(() = > {
done = false;
}, time)
}
}
Copy the code
Function anti – shake and throttling refer to this article.
4. Listen for scrolling events. In fact, the implementation principle here is the same as the JavaScript implementation version, but with a slight change of thinking.
7. Split Landing Page
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
8.Form Wave
The effect is as follows:
- The source code
- Online sample
What did you learn?
- SetState updates an object. If state is an object, we have 2 ways to update it. 1.1 Use the Object.assign method to update. 1.2 Overwrite the entire object directly.
The pseudocodes of the above two methods are as follows:
// The first way
const loginInfo = Object.assign({},this.state.loginInfo,{
[key]:updateValue
})
this.setState({
loginInfo
});
// The second way
let { loginInfo } = this.state;
loginInfo[key] = updateValue;
this.setState({ loginInfo });
Copy the code
9.Sound Board
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
10. Dad Jokes
The effect is as follows:
- The source code
- Online sample
What did you learn?
-
Use of Suspense components. This component can specify a load indicator component for lazy loading of components. Suspense for more detailed documentation.
-
Interface requests are typically done in the componentDidMount hook function. Since you cannot change the state directly in this hook function (react.js gives you a warning). So we need to make the interface request asynchronous.
11. Event Keycodes
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
12. Faq Collapse
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
13. Random Choice Picker
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
14. Animated Navigation
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
15. Incrementing Counter
The effect is as follows:
- The source code
- Online sample
What did you learn?
- How does react.js update an item in an array? In this case, I’m updating the entire array, which is probably not a good way to do it. I’d love to have some ideas. My code is as follows:
startCounter() {
const counterList = [...this.state.counterList];
// https://stackoverflow.com/questions/29537299/react-how-to-update-state-item1-in-state-using-setstate
// https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-react-js
counterList.forEach(counter= > {
const updateCounter = () = > {
const value = counter.value;
const increment = value / 100;
if (counter.initValue < value) {
counter.initValue = Math.ceil(counter.initValue + increment);
// use setTimeout or setInterval ?
counter.timer = setTimeout(updateCounter, 60);
} else {
counter.initValue = value;
clearTimeout(counter.timer);
}
// update the array,maybe it's not a best way,is there any other way?
this.setState({ counterList }); } updateCounter(); })}Copy the code
16. Drink Water
The effect is as follows:
- The source code
- Online sample
What did you learn?
- There is a pit here, and using new Array().fill() to initialize the state will result in an unexpected rendering effect. So we’re directly initializing all the array items.
See the source code.
17. movie-app
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
PS: This sample effect requires you to understand the access due to limited interface access.
18. background-slider
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
19. theme-clock
The effect is as follows:
- The source code
- Online sample
What did you learn?
- Chinese-english switching is done by defining an object. Nothing else to say, are mentioned in front of the knowledge point.
PS: This example also uses the same utility function as in Example 5, the scale function
20. button-ripple-effect
The effect is as follows:
- The source code
- Online sample
What did you learn?
- You can render a component by calling a function.
21. drawing-app
The effect is as follows:
- The source code
- Online sample
What did you learn?
- Used in react.js
ew-color-picker
. - There is a pit here, which means you have to set the style of the line.
this.ctx.lineCap = "round";
Copy the code
Otherwise the lines don’t look right, although I don’t really know why. After all, the JS version of the implementation does not need to display the style to set this line.
22. drag-n-drop
The effect is as follows:
- The source code
- Online sample
What did you learn?
- Here also stepped on a pit, see the source notes.
23. content-placeholder
The effect is as follows:
- The source code
- Online sample
What did you learn?
- Some utility functions for determining the React component. As follows:
import React from "react";
export function isString(value){
return typeof value === "string";
}
export function isClassComponent(component) {
return typeof component === 'function'&&!!!!! component.prototype.isReactComponent; }export function isFunctionComponent(component) {
return typeof component === 'function' && String(component).indexOf('return React.createElement') > -1;
}
export function isReactComponent(component) {
return isClassComponent(component) || isFunctionComponent(component);
}
export function isElement(element) {
return React.isValidElement(element);
}
export function isDOMTypeElement(element) {
return isElement(element) && typeof element.type === 'string';
}
export function isCompositeTypeElement(element) {
return isElement(element) && typeof element.type === 'function';
}
Copy the code
- How to wrap a card component.
24. kinetic-loader
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example covers all the points mentioned in previous examples, so there is no need to repeat them here.
25. sticky-navbar
The effect is as follows:
- The source code
- Online sample
What did you learn?
Except for one tool function, this example covers all the points mentioned in the previous example, so there is no need to repeat them here.
export function marked(template){
return template.replace(/. +? [\s]/g.v= > `<p>${v}</p>`);
}
Copy the code
The utility function matches any character ending in a space and wraps it with a P tag.
PS: Mobile layout is also done here.
26. double-slider
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
27. toast-notification
The effect is as follows:
- The source code
- Online sample
What did you learn?
-
You can use reactdom.render to encapsulate the toast component of a function call.
-
ReactDOM. UnmountComponentAtNode API usage of this method will unload components from the DOM, including event handler and the state. See documentation for details.
-
GetDerivedStateFromProps Static function. See documentation for details.
28. github-profiles
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
29. double-click-heart
The effect is as follows:
- The source code
- Online sample
What did you learn?
- Read the native event object from the synthesized event object. namely
nativeEvent
Properties.
30. auto-text-effect
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
31. password generator
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
32. good-cheap-fast
The effect is as follows:
- The source code
- Online sample
What did you learn?
- How to encapsulate a switch component, the switch component.
33. notes-app
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
34. animated-countdown
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
35. image-carousel
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
36. hover board
The effect is as follows:
- The source code
- Online sample
What did you learn?
- SetState in the react.js synthetic event is synchronous, so native listener events are used here. See the source code.
37. pokedex
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
38. mobile-tab-navigation
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
39. password-strength-background
The effect is as follows:
- The source code
- Online sample
What did you learn?
- According to theThe documentStep by step to
tailwindcss
Added to thecreate-react-app
In the scaffolding.
40. 3D-background-boxes
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
41. Verify Your Account
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
42. live-user-filter
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
43. feedback-ui-design
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
44. custom-range-slider
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
45. netflix-mobile-navigation
The effect is as follows:
- The source code
- Online sample
What did you learn?
- Provides ideas for how to implement a recursive component.
46. quiz-app
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
47. testimonial-box-switcher
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
48. random-image-feed
The effect is as follows:
- The source code
- Online sample
What did you learn?
- Implement a simple version of the preview image.
49. todo-list
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
50. insect-catch-game
The effect is as follows:
- The source code
- Online sample
What did you learn?
This example will cover all the points mentioned in previous examples, so there is no need to repeat them here.
Special note: this example is a more comprehensive example.