2022 front end social recruitment React interview questions with answers
React Video Explanation Click to learn
All videos: Click to learn
1. What is the implementation principle of react router?
The idea of client routing implementation:
hash Based Routing: by listening
hashchange
Event, sensing the change of hash
- You can change the hash directly through location.hash=xxx
H5 history based routing:
- You can change the URL through history.pushState and repositionstate, which will push the URL into the stack and apply API s such as history.go()
- Monitoring url changes can be triggered by custom events
The idea of react router implementation:
- The above different client routing implementation ideas are realized based on the history library, and the history records can be saved to smooth out the browser differences without being perceived by the upper layer
- Through the maintained list, recycle every time the URL changes, match the corresponding Component through the configured routing path, and render
2. How to configure react router to realize route switching
(1) Using the < route > component
Route matching is achieved by comparing the path attribute of < route > with the pathname of the current address. When a < route > match is successful, it will render its content, and when it does not match, it will render null. < route > without a path will always be matched.
// when location = { pathname: '/about' } <Route path='/about' component={About}/> // renders <About/> <Route path='/contact' component={Contact}/> // renders null <Route component={Always}/> // renders <Always/> Copy code
(2) Use a combination of < Switch > components and < route > components
< Switch > is used to group < route >.
<Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/contact" component={Contact} /> </Switch> Copy code
< Switch > is not necessary for grouping < route >, but it is usually useful. A < Switch > traverses all its child < route > elements and renders only the first element that matches the current address.
(3) Use < link >, < navlink >, < redirect > components
< link > component to create links in your application. Wherever you render a < link >, the anchor will be rendered in the HTML of the application (< a >).
<Link to="/">Home</Link> // <a href='/'>Home</a> Copy code
Is a special type. When its to attribute matches the current address, it can be defined as "active".
// location = { pathname: '/react' } <NavLink to="/react" activeClassName="hurray"> React </NavLink> // <a href='/react' className='hurray'>React</a> Copy code
When we want to force navigation, we can render a < redirect >, and when a < redirect > is rendered, it will use its to attribute for orientation.
3. How to set redirection for react router?
Use the < redirect > component to redirect routes:
<Switch> <Redirect from='/users/:id' to='/users/profile/:id'/> <Route path='/users/profile/:id' component={Profile}/> </Switch> Copy code
When the request / users/:id is redirected to '/ users/profile/:id':
- Attribute from: string: the path to be redirected that needs to be matched.
- Property to: string: redirected URL string
- Attribute to: object: redirected location object
- Attribute push: bool: if true, the redirection operation will add the new address to the access history and cannot go back to the previous page.
4. Difference between Link tag and a tag in react router
From the DOM of the final rendering, both of them are links and labels. The difference is that < link > is a link to realize route jump in the react route, which is generally used in conjunction with < route >. The react route takes over its default link jump behavior, which is different from the traditional page jump. The "jump" behavior of < link > will only trigger the page content update corresponding to the matching < route >, Instead of refreshing the entire page.
< link > did three things:
- If there is onclick, execute onclick
- Block a tag default event when click ing
- According to the jump href (i.e. to), jump with history (History & hash, one of the two methods of Web front-end routing). At this time, only the link changes and the page is not refreshed. The < a > tag is an ordinary hyperlink, which is used to jump from the current page to another page pointed to by the href (non anchor).
What is done to jump after the default event of tag a is disabled?
let domArr = document.getElementsByTagName('a') [...domArr].forEach(item=>{ item.addEventListener('click',function () { location.href = this.href }) })
5. How does react router get the parameters and historical objects of the URL?
(1) Get parameters for URL
- get pass value
The routing configuration is also a normal configuration, such as' admin ', and the parameter transfer method is such as' admin?id='1111'. Get the url through this.props.location.search and get a string '? id='1111 'you can use url, qs, querystring, the api URLSearchParams object provided by the browser, or your own encapsulated method to parse the id value.
- Dynamic routing value transmission
The route needs to be configured as a dynamic route, such as path='/admin/:id', and the parameter transmission method, such as' admin/111 '. this.props.match.params.id is used to obtain the value of the dynamic route ID part in the url. In addition, it can also be obtained through useParams (Hooks)
- Pass values through query or state
For example, the object {pathname:'/admin',query:'111',state:'111'} can be passed in the to attribute of the Link component;. It can be obtained through this.props.location.state or this.props.location.query. The parameters passed can be objects, arrays, etc., but the disadvantage is that as long as the page is refreshed, the parameters will be lost.
(2) Get history object
- If react > = 16.8, you can use Hooks provided in React Router
import { useHistory } from "react-router-dom"; let history = useHistory(); Copy code
2. Use this.props.history to get the history object
let history = this.props.history;
6: What is refs used in React?
Subject: React
Difficulty: ⭐⭐
Refs provides a way to access DOM nodes or React elements created in the render method. In a typical data stream, props is the only way for parent-child components to interact. If you want to modify a child component, you need to re render it with a new pro. There are exceptions. In some cases, we need to force the modification of children outside the typical data flow. Refs can be used at this time.
We can add a ref attribute to the component. The value of this attribute is a callback function that receives the mounted instance of the underlying DOM element or component as its first parameter.
class UnControlledForm extends Component { handleSubmit = () => { console.log("Input Value: ", this.input.value) } render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' ref={(input) => this.input = input} /> <button type='submit'>Submit</button> </form> ) } } Copy code
Note that the input element has a ref attribute whose value is a function. This function takes the actual DOM element of the input and places it on the instance so that it can be accessed inside the handleSubmit function.
It is often misunderstood that refs can only be used in class components, but refs can also be used with function components by using closures in JS.
function CustomForm ({handleSubmit}) { let inputElement return ( <form onSubmit={() => handleSubmit(inputElement.value)}> <input type='text' ref={(input) => inputElement = input} /> <button type='submit'>Submit</button> </form> ) }
7: How to handle events in React
Subject: React
Difficulty: ⭐⭐
In order to solve the problem of cross browser compatibility, the SyntheticEvent instance will be passed to your event handler. SyntheticEvent is the browser native event wrapper of React cross browser. It also has the same interface as the browser native event, including stopPropagation() and preventDefault().
Interestingly, react does not actually attach events to the child nodes themselves. React uses a single event listener to listen for all events at the top level. This is good for performance and means that react does not need to track event listeners when updating the DOM.
8: How to create refs
Subject: React
Difficulty: ⭐⭐
Refs is created using React.createRef() and attached to the React element through the ref attribute. When constructing components, refs are usually assigned to instance properties so that they can be referenced throughout the component.
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} />; } } Copy code
Or use this:
class UserForm extends Component { handleSubmit = () => { console.log("Input Value is: ", this.input.value) } render () { return ( <form onSubmit={this.handleSubmit}> <input type='text' ref={(input) => this.input = input} /> // Access DOM input in handle submit <button type='submit'>Submit</button> </form> ) } }
9: What is the function of calling super in the constructor and passing props as a parameter?
Subject: React
Difficulty: ⭐⭐
The subclass constructor cannot use this reference until the super() method is called, as can the ES6 subclass. The main reason for passing the props parameter to the super() call is that the passed in props can be obtained through this.props in the sub constructor.
Pass props
class MyComponent extends React.Component { constructor(props) { super(props); console.log(this.props); // { name: 'sudheer',age: 30 } } } Copy code
No props passed
class MyComponent extends React.Component { constructor(props) { super(); console.log(this.props); // undefined // However, the Props parameter is still available console.log(props); // Prints { name: 'sudheer',age: 30 } } render() { // Constructors outside are not affected console.log(this.props) // { name: 'sudheer',age: 30 } } } Copy code
The above example reveals one point. The behavior of props is different only in the constructor, but also outside the constructor.
10: How to React.createElement?
Subject: React
Difficulty: ⭐⭐⭐
Question:
const element = ( <h1 className="greeting"> Hello, world! </h1> ) Copy code
How to use React.createElement in the above code:
const element = React.createElement( 'h1', {className: 'greeting'}, 'Hello, world!' );