The fork by github.com/sudheerj/re… Is the translation of the links above, but also deepen their understanding of part + complement (italics) continuously updated: www.yuque.com/3crazyone/c…
The React core
1. What is React
Is an open source JavaScript library for building user pages, especially single-page applications, focusing on the view layer of Web and mobile applications. Originally developed by Facebook engineer Jordan Walke, it was first used in Facebook’s newsfeed in 2011 and first applied to Instagram in 2012.
2. What are the main features of React
- Use virtual DOM instead of real DOM to reduce DOM operation overhead
- Follow one-way data flow/data binding
- Develop views using reusable/composable UI components
- Support for server-side rendering
3. What is JSX
JSX is an ECMAScript-based xmL-class syntax extension that provides syntactic sugar for the react.createElement () function so it can be developed in JAVASCRIPT using HTML templates that are easier to understand.
In the example below, the text inside the
tag is returned to the Render function as a JavaScript function.
class App extends React.Component {
render() {
return(
<div>
<h1>{'Welcome to React world! '}</h1>
</div>)}}Copy the code
What is the difference between an Element and a Component
The element is a plain object that describes what you want to display on the screen, based on a DOM node or other component. An element can contain other elements in its props. Creating a React element is simple. Once an element is created, it does not change.
The React element’s object looks like this:
const element = React.createElement(
'div',
{id: 'login-btn'},
'Login'
)
Copy the code
React.createElement returns an object:
{
type: 'div'.props: {
children: 'Login'.id: 'login-btn'}}Copy the code
Finally, it renders to the DOM using reactdom.render () :
<div id='login-btn'>Login</div>
Copy the code
Components can be declared in several different ways. It can be a class with the Render () method. Or, in simple cases, you can define it as a function. In both cases, it accepts props as input and returns a JSX structure as output
const Button = ({ onLogin }) =>
<div id={'login-btn'} onClick={onLogin}>Login</div>
Copy the code
JSX is then converted to one via react.createElement () :
const Button = ({ onLogin }) = > React.createElement(
'div',
{ id: 'login-btn'.onClick: onLogin },
'Login'
)
Copy the code
5. How to create a component
There are two ways to create a component:
- Functional components: This is an easy way to create components. Just like a simple JS function, it takes props as the first argument and returns the React element:
function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>
}
Copy the code
- Class component: You can also define a component using ES6 class syntax sugar, and the above function component is written in class component:
class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>}}Copy the code
6. When to use class components instead of function components
Use class components if components need to use state or lifecycle methods, otherwise use function components. However, React 16.8 includes hooks, so function components can use state, lifecycle and other features as well.
7. What is Pure Component
React.purecomponent is the same as react.componentexcept that it handles shouleComponentUpdate() when the props or state is changed, The PureComponent makes a shallow comparison between props and state. Component, on the other hand, does not compare the current props and state with the next update. Therefore, every time shouldComponentUpdate is called, the component will be rerendered by default.
8. What is the React state
A component’s state is an object that contains some information that can change during the lifetime of the component. We should make state as simple as possible and reduce the number of components that have state. Let’s create a user component with message status:
class User extends React.Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome to React world'
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>)}}Copy the code
9. What are the React props
Props is the input to the component. They are a single value or object containing a set of values that are passed to the component when created using a naming convention similar to the HTML-tag attribute. They are data passed from parent to child components.
The main purpose of the Props in React is to provide the following component functions:
- Pass custom data to the component.
- Trigger a state change.
- In the render() method of the component, using this.props.
For example, let’s create an element and give it a reactProp property:
<Element reactProp={'1'} / >Copy the code
The reactProp will then become a property attached to the React native Props object, which originally existed on all components created using React.
props.reactProp
Copy the code
10. What is the difference between state and props
Prop and state are plain JS objects. Although they both have information that affects the rendered output, they differ in their component-wise functionality. Props is passed to the component as an argument to a function, and state is managed within the component like variables declared in a function.
11. Why not update state directly
Updating State directly as follows does not trigger component rerendering
this.state.message = 'Hello world'
Copy the code
You need to update the state object with setState, and when state changes, the component is rerendered
this.setState({ message: 'Hello World' })
Copy the code
12. What is the purpose of using callback functions as arguments in setState
The callback function is executed after the setState execution is complete and the component has finished rendering. Since setState is executed asynchronously, the callback function can be used as a subsequent operation after a state update.
Note: It is recommended to use the lifecycle method instead of this callback function.
setState(
{
name: 'John'}, () = >console.log('The name has updated and component re-rendered'))Copy the code
What is the difference between the HTML event binding and the React event binding
- In HTML, binding event names should be all lowercase:
<button onclick='activateLasers()'>
Copy the code
- React uses a small hump:
<button onClick={activateLasers}>
Copy the code
- In HTML, you can use return false to prevent the default behavior:
<a href=The '#' onclick='console.log("The link was clicked."); return false; ' />
Copy the code
- PreventDefault must be used in React
function handleClick(event) {
event.preventDefault()
console.log('The link was clicked.')}Copy the code
- In HTML, you’re supposed to use functions with a () after the function name, but in React you don’t,See also the previous example. HTML uses strings, while React uses {}.
_
14. How do I bind methods and event handling in JSX
There are 3 ways to do this:
- Bind a Constructor: In JS classes, methods are not bound by default. The same goes for the class components used to construct React. Usually we bind them in constructors
class Component extends React.Componenet {
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
// ...}}Copy the code
- Use arrow functions: You can define public methods using arrow functions or add anonymous functions directly to JSX objects instead of using bind
handleClick = () => { console.log('this is:', this) } <button onClick={this.handleClick}> {'Click me'} </button> <button onClick={(event) => this.handleClick(event)}> {'Click me'} </button>Copy the code
15. How to bind event or callback function data pass parameter
You can use arrow functions to bind wrapped events and pass parameters
<button onClick={() => this.handleClick(id)} />
Copy the code
You can also use bind
<button onClick={this.handleClick.bind(this, id)} />
Copy the code
Or you can use higher-order functions
handleClick = (id) = >() = > {console.log("Hello, your ticket number is", id)
};
<button onClick={this.handleClick(id)} />
Copy the code
15. How to bind event or callback function data pass parameter
You can use arrow functions to bind wrapped events and pass parameters
<button onClick={() => this.handleClick(id)} />
Copy the code
You can also use bind
<button onClick={this.handleClick.bind(this, id)} />
Copy the code
Or you can use higher-order functions
handleClick = (id) = >() = > {console.log("Hello, your ticket number is", id)
};
<button onClick={this.handleClick(id)} />
Copy the code
16. What is the React composite event
Synthetic events are cross-browser wrappers around browser-native events. In addition to being compatible with all browsers, it has the same interface as browser native events. Including stopPropagation() and preventDefault()
17. What is an inline conditional expression
You can conditionally render expressions using if statements or ternary expressions. You can also embed any expression in JSX by wrapping it in curly braces and then using JS logical operators such as && :
<h1>Hello!</h1>
{
messages.length > 0 && !isLogin?
<h2>
You have {messages.length} unread messages.
</h2>
:
<h2>
You don't have unread messages.
</h2>
}
Copy the code
18. What’s key? What are the benefits of using it in array elements?
A key is a special string attribute that should be included when creating an array of elements. The key is used to help React identify items that have changed, been added, or removed. We often use ids in our data as keys:
const todoItems = todos.map((todo) =>
<li key={todo.id}>
{todo.text}
</li>
)
Copy the code
You can also use an array index if you don’t have a suitable ID, but it is recommended as a last resort:
const todoItems = todos.map((todo, index) =>
<li key={index}>
{todo.text}
</li>
)
Copy the code
Notes:
- Indexes are not recommended if the order of rendering elements can change. This can have a negative impact on performance and can lead to problems with component state.
- If each array element is extracted as a separate component, the key is applied to the component instead of the LI tag.
- If the key is not a list item prop, a warning message is displayed in the console.
19. What are refs for
Ref is used to return a reference to an element. They should be avoided in most cases, but can be useful if you need direct access to an instance of a DOM element or component.
20. How do I create refs
There are several ways to create:
- Use the hooks useRef to create the latest application:
const MyComponent = (a)= > {
const myRef = useRef()
return <div ref={this.myRef} /> // use myRef.current
}
Copy the code
- This is also a relatively new approach. Use the React.createref () method to create a reference and attach it to the React element via the ref attribute. To use the reference throughout the component, simply assign the reference to the instance property in the constructor:
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
}
render() {
return}}Copy the code
- The REF callback method can be used regardless of the React version. For example, access the input elements of the search bar component as follows:
class SearchBar extends Component {
constructor(props) {
super(props);
this.txtSearch = null;
this.state = { term: ' ' };
this.setInputSearchRef = e= > {
this.txtSearch = e;
}
}
onInputChange(event) {
this.setState({ term: this.txtSearch.value });
}
render() {
return (
<input
value={this.state.term}
onChange={this.onInputChange.bind(this)}
ref={this.setInputSearchRef} />); }}Copy the code
Refs can also be used with closures using function components. Note: Inline reference callbacks can also be used, even if it is not a recommended approach
21. What are forward refs
Ref Forwarding is a new feature that allows some components to receive the Refs they receive and pass them on to child components, simply passing the Refs through _
const ButtonElement = React.forwardRef((props, ref) = > (
<button ref={ref} className="CustomButton">
{props.children}
</button>
));
// Create ref to the DOM button:
const ref = React.createRef();
<ButtonElement ref={ref}>{'Forward Ref'}</ButtonElement>
Copy the code
22. Refs and findDOMNode() should select that
It is best to use refs instead of the findDOMNode() API. Because findDOMNode() will prevent some improvements to React in the future, here’s an example using findDOMNode:
class MyComponent extends Component {
componentDidMount() {
findDOMNode(this).scrollIntoView()
}
render() {
return <div />}}Copy the code
Use refs instead:
class MyComponent extends Component {
constructor(props){
super(props);
this.node = createRef();
}
componentDidMount() {
this.node.current.scrollIntoView();
}
render() {
return <div ref={this.node} />}}Copy the code
23. Why string Refs are abandoned (need to be perfected)
Those of you who have used React before will know an older API where the ref attribute is a string, such as ref = {‘textInput’}, and the DOM node is accessed as this.refs.textinput. We recommend against this because string references have the following problems and are considered legacy issues. React V16 removes string references:
- Forcing React to keep track of what components are currently in use is problematic because it makes the React module stateful and therefore causes strange errors when copying the React module in bundles.
- Non-combinable – If a library has a ref added to the passed child, the user cannot add a ref to it. The refs of callbacks can be combined.
- They are not suitable for static analysis such as Flow. Flow cannot guess at the effect of the framework making the string ref appear on this.refs and its type (which may vary). Refs for callbacks are friendlier than static analysis.
- You can’t use the “render callback” mode that most people expect
class MyComponent extends Component {
renderRow = (index) = > {
// This will not work, ref will be added to DataTable instead of MyComponent
return<input ref={'input-' + index} />; Return <input ref={input => this['input-' + index] = input} />; } render() { return <DataTable data={this.props.data} renderRow={this.renderRow} /> } }Copy the code
24. What is the virtual DOM
The virtual DOM (VDOM) is an in-memory representation of the real DOM (which is actually an object). The REPRESENTATION of the UI is kept in memory and synchronized with the “real” DOM. This is a step in the process of calling the render function and displaying elements on the screen. The whole process is called Reconciliation.
25. How does the virtual DOM work
The virtual DOM can be broken down into three simple steps
- Whenever any underlying data changes, the entire UI is recalculated and rendered in a virtual DOM representation
- Compute the difference between the previous DOM tree and the new DOM tree
- Once the calculation is complete, the actual DOM will update only the parts that need to be changed
26. What is the difference between Shadow DOM and virtual DOM
Shadow DOM is a browser-native support technique used to determine the scope of variables and CSS in Web Components. The virtual DOM is a method implemented on top of the browser API.
27. What is React Fiber
Fiber is a new Reconciliation engine or re-implementation of the core algorithms in React V16. React Fiber aims to improve its applicability for animations, layouts, gestures, pauses, pauses, or reuse, and assigns priorities to different types of updates, as well as new?? Concurrency primitives??
28. What is the main purpose of React Fiber
React Fiber aims to enhance its usability in areas like animation, layout, and gestures. Its main feature is incremental rendering: the ability to split the rendering effort into chunks and spread it out over multiple frames
29. What is a controlled component
A controlled component is a component that controls subsequent user input to the input element of the form, with a corresponding handler for each state change. As in the following example, we change all of our inputs to uppercase, which we use handleChange to control:
handleChange(event) {
this.setState({value: event.target.value.toUpperCase()})
}
Copy the code
30. What is an uncontrolled component
An uncontrolled component is a component that stores its own state internally, using ref to query the DOM for its current value when needed, much like traditional HTML. The following UserProfile component uses ref to get the name in the input:
class UserProfile extends React.Component {
constructor(props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
this.input = React.createRef()
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value)
event.preventDefault()
}
render() {
return( <form onSubmit={this.handleSubmit}> <label> {'Name:'} <input type="text" ref={this.input} /> </label> <input type="submit" value="Submit" /> </form> ); }}Copy the code
Note: In most cases, it is recommended to implement forms using controlled components
31. What is the difference between cloneElement and createElement
JSX uses the React.createelemen () function to transform the React element into an object and render it into the UI, while cloneElement is used to clone the element and pass the new props.
32. What are state boosts in React
When multiple components need to share the same changed data, it is recommended that the shared state be promoted to the nearest public parent. That is, if two child components share the same data from their parent, then state is moved to the parent rather than keeping the data private in each child. ,
33. What are the different phases of the component life cycle
There are three distinct phases in the component life cycle
- Mounting: The component is ready to mount in the DOM. This phase includes the following methods for component initialization
- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount()
- Updating: During this phase, components are updated in two ways, receiving new props and Updating the state using setState() or forceUpdate(). This phase includes:
- getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()
- Unmounting: The component is unmounted from the DOM in the final stage when it is no longer needed. This stage includes:
- componentWillUnmount()
It’s worth knowing that React also has a concept of phases within it when applying changes to the DOM. They are separated as follows:
- Render: Components will Render without any side effects. This applies to Pure components, where React can pause, halt, or restart rendering.
- Pre-commit: Allow React to read the DOM via getSnapshotBeforeUpdate for a period of time before the component actually applies the changes to the DOM.
- Commit: React works with the DOM and performs the final life cycle separately: componentDidMount for installation, componentDidUpdate for updates, and componentWillUnmount for uninstallation.
The React lifecycle was changed after 16.3.
34. React lifecycle methods are available
The React 16.3 +
- GetDerivedStateFromProps: Called immediately before render is called, and on each renderer. This exists for rare use cases that require derived state. If you need to derive state, it’s worth reading.
- ComponentDidMount: Executed after the first rendering, this is where all network/Ajax requests, get/manipulate DOM or state updates, and bind listening events should occur.
- ShouldComponentUpdate: Determines whether to update the component. By default, it returns true. Return false if you determine that the component does not need to render after a status or item update. This is a good place to improve performance, as it prevents re-rendering if the component receives a new item.
- GetSnapshotBeforeUpdate: Executes immediately before rendering the output to the DOM. Any value returned from this is passed to componentDidUpdate. This is useful for capturing information from the DOM, the scrolling position.
- ComponentDidUpdate: Typically used to update the DOM in response to property or state changes. If shouldComponentUpdate returns false, it will not fire.
- ComponentWillUnmount This will be used to cancel any outgoing network requests or remove any listening events associated with the component.
React 16.3 before:
- ComponentWillMount: Executed before rendering for app-level configuration in the root component.
- ComponentDidMount: same as above
- ComponentWillReceiveProps: in particular update props to trigger a state transition.
- ShouldComponentUpdate: same as above
- ComponentWillUpdate: Executed before rerendering the component when shouldComponentUpdate, which should return true, confirms props and state changes.
- ComponentDidUpdate: same as above
- ComponentWillUnmount: same as above
35. What are higher-order components
HOC is actually a function that accepts a component as a parameter and returns a new component as a parameter. It is a design pattern formed based on the combination features of React.
We call them pure components because they can accept any dynamically supplied child component, but they do not modify or copy any behavior in the input component
const EnhancedComponent = higherOrderComponent(WrappedComponent)
Copy the code
Use cases for HOC:
- Code, logic reuse and abstraction
- Rendering hijacked
- State abstraction and manipulation
- Props operation
36. If you want to create the props agent for higher-order components
You can use the props proxy mode to add or edit props passed to the component, as shown below:
function HOC(WrappedComponent) {
return class Test extends Component {
render() {
const newProps = {
title: 'New Header'.footer: false.showFeatureX: false.showFeatureY: true
}
return <WrappedComponent {. this.props} {. newProps} / >}}}Copy the code
37. What is context
Context provides a way to pass data across the component tree without having to pass props manually at each level. For example, authenticated users, regions, language preferences, and UI themes need to be accessed by many components in the application.
const {Provider, Consumer} = React.createContext(defaultValue)
Copy the code
38. What are the children passed in props
Children is a props(this.prop.children), which allows components to be passed as data to other components, just like any other props used. Components placed between components are passed to that component as child components. There are a number of methods available in the React API for this prop. These include
- React.Children.map
- React.Children.forEach
- React.Children.count
- React.Children.only
- React.Children.toArray
The simple usage is as follows:
const MyDiv = React.createClass({
render: function() {
return <div>{this.props.children}</div>
}
})
ReactDOM.render(
<MyDiv>
<span>{'Hello'}</span>
<span>{'World'}</span>
</MyDiv>,
node
)
Copy the code
39. How to write comments in React
Comments in React/JSX are similar to JavaScript multi-line comments, but need to be wrapped in curly braces:
<div>
{/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */}
{`Welcome ${user}, let's play React`}
</div>
Copy the code
Multi-line comments:
<div>
{/* Multi-line comments for more than
one line */}
{`Welcome ${user}, let's play React`}
</div>
Copy the code
40. What does the constructor do when props is passed as a parameter to super
The subclass constructor cannot use this reference until the super() method is called. The same applies to ES6 subclasses. The main reason for passing the props argument to the super() call is so that this.props can be used in the child constructor. Pass props
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(this.props) // prints { name: 'John', age: 42 }}}Copy the code
Don’t pass props:
class MyComponent extends React.Component {
constructor(props) {
super(a)console.log(this.props) // prints undefined
// but props parameter is still available
console.log(props) // prints { name: 'John', age: 42 }
}
render() {
// no difference outside constructor
console.log(this.props) // prints { name: 'John', age: 42 }}}Copy the code
What is reconciliation?
When a component’s props or state changes, React compares the newly returned element with the previously rendered element to determine if it needs to perform a DOM update. React updates the DOM when the current element is not equal. This process is called reconciliation
42. If you set state to a variable
If you use ES6 or Babel to transform JSX code, you can do this using the calculated property names.
handleInputChange(event) {
this.setState({ [event.target.id]: event.target.value })
}
Copy the code
43. What is a common mistake in calling a function every time a component renders
When passing a function as an argument, you need to make sure that the function is not called:
render() {
// Wrong: handleClick was called and clicking will no longer trigger the function
return <button onClick={this.handleClick()}>{'Click Me'}</button>
}
Copy the code
The correct way is:
render() {
return <button onClick={this.handleClick}>{'Click Me'}</button>
}
Copy the code
44. Do lazy functions support files with multiple exports
React.lazy currently only supports files that are exported by default. If you want to import a module under Exports, you can create an intermediate module and re-export it as the default module. It also ensures that the component tree remains healthy and that unused components are not associated. Let’s take exporting component files with multiple named components as an example
// MoreComponents.js
export const SomeComponent = / *... * /;
export const UnusedComponent = / *... * /;
Copy the code
Export more component.js components in an intermediate file, intermediatecomponent.js
// IntermediateComponent.js
export { SomeComponent as default } from "./MoreComponents.js";
Copy the code
You can now import the file and use lazy
import React, { lazy } from 'react';
const SomeComponent = lazy((a)= > import("./IntermediateComponent.js"));
Copy the code
45. Why does React use className instead of class
Class is a keyword in JavaScript, and JSX is a JavaScript extension, which is the main reason why React uses className instead of class. Pass a string as className prop.
46. What are fragments
This is a common pattern in React for components to return multiple elements, and Fragments allow you to group lists of subitems without adding additional nodes to the DOM.
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>)}Copy the code
Grammar sugar can also be used
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>)}Copy the code
47. Why are fragments better wrapped than DOM?
- Fragments are faster and use less memory because no additional DOM nodes are created. This has real benefits for large, deep DOM trees.
- Some CSS mechanisms (such as Flexbox and CSS Grid) have a special parent-child relationship, and adding divs in the middle makes it difficult to maintain the desired layout.
- The DOM inspector is neat
48. What is portals
Portal is the recommended method for rendering child components to DOM nodes that exist outside the PARENT component’s DOM hierarchy.
ReactDOM.createPortal(child, container)
Copy the code
The first argument is any renderable React child element, such as an element, string, or fragment. The second argument is the DOM element.
Chinese official documents is introduced: zh-hans.reactjs.org/docs/portal…
49. What is stateless component
A component can be stateless if it behaves independently of its state. You can create function components or class components to represent stateless components. However, if you do not need to use lifecycle methods, it is recommended to use function components. There are many benefits to using functional components, such as they are easy to write, understand, and test, faster, and you can completely avoid using the this keyword.
50. What is stateful component
A component can be called stateful if its behavior depends on its state. These stateful components typically use class components and have initialized state in constructors. React 16.8 uses hooks to generate stateful components in function components:
class App extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
render() {
// ...}}Copy the code
Using hook
import React, {useState} from 'react';
const App = (props) = > {
const [count, setCount] = useState(0);
return (
// JSX)}Copy the code
How to verify props in React
When the application is running in development mode, React automatically checks all the props we set up on the component to make sure they are of the correct type. React generates a warning message in the console if the type is incorrect. It is disabled in production mode due to performance concerns. The props that must be passed in is defined with isRequired. The predefined types are as follows:
- PropTypes.number
- PropTypes.string
- PropTypes.array
- PropTypes.object
- PropTypes.func
- PropTypes.node
- PropTypes.element
- PropTypes.bool
- PropTypes.symbol
- PropTypes.any
Take a look at this example where we use propTypes in the User component
import React from 'react'
import PropTypes from 'prop-types'
class User extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
render() {
return (
<>
<h1>{`Welcome, ${this.props.name}`}</h1>
<h2>{`Age, ${this.props.age}`}</h2>
</>)}}Copy the code
52. What’s the React advantage
- The performance of the program is improved through the virtual DOM
- JSX makes code easy to write and read
- Support local rendering and server-side rendering
- Easy to integrate with other frameworks because it’s just a view layer
- Easy to write integration and unit testing tools such as Jest
53. What are the limitations of React
- React is just a view layer, not a complete framework
- There is a learning curve for beginners and newcomers
- Integrating React into a traditional MVC framework requires some additional configuration
- Inline templates and JSX add complexity to the code
- Too many smaller components lead to excessive engineering or boilerplate