Hi, I’m @Luo Zhu

This article was first published on luo Zhu’s official website

Translated from Sudheerj/reactJs-interlocution-Questions

This article synchronizes in the public account Luo Zhu early teahouse, reprint please contact the author.

  • React Interview QUESTION 选 择 Day1

1. Why can’t we just update our status?

The React component does not rerender if you try to update the state directly.

/ / error ❌
this.state.message = 'Hello world';
Copy the code

The correct approach is to use the setState() method. It plans an update to the component state object. When the state changes, the component responds by rerendering.

/ / ✅ correctly
this.setState({ message: 'Hello World' });
Copy the code

** Note: ** You can assign it directly to a state object using constructors or the latest javascript class field declaration syntax.

2. Callback function assetState()What is the purpose of the parameter?

After setState completes and rerenders the component, the callback function is called. Because setState() is asynchronous, the callback function can be used for any subsequent operation.

** Note: ** We recommend using the lifecycle method instead of this callback function

setState({ name: 'John' }, () = >
  console.log('The name has updated and component re-rendered'));Copy the code

3. What is the difference between HTML and React event handling?

Here are some of the main differences between HTML and React event handling:

  1. In HTML, event names should be all lowercase:
<button onclick="activateLasers()"></button>
Copy the code

However, in React event names follow the small hump format:

<button onClick={activateLasers}>
Copy the code
  1. In HTML, you should returnfalseTo prevent the default behavior:
<a href="#" onclick='console.log("The link was clicked."); return false; ' />
Copy the code

Then in React you have to explicitly call preventDefault()

function handleClick(event) {
  event.preventDefault();
  console.log('The link was clicked.');
}
Copy the code
  1. In HTML, when you call a function, you add(a):

Then in React you shouldn’t put a () after the function name. (Such as the activateLasers function in the previous example)

4. How to bind a method or event handler in a JSX callback function

Here are 3 ways to do this:

  1. Bind in constructor: In JavaScript classes, methods are not bound by default. The same thing applies to React event handlers defined as class methods. Usually we bind them in constructors.
class Component extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // ...}}Copy the code
  1. Class public field syntax: If you don’t like binding, you can use the class public field syntax to bind callbacks correctly:
handleClick = () = > {
  console.log('this is:'.this);
};
Copy the code
<button onClick={this.handleClick}>{'Click me'}</button>
Copy the code
  1. Arrow functions as callbacks: You can use arrow functions directly in callbacks
<button onClick={event= > this.handleClick(event)}>{'Click me'}</button>
Copy the code

Note: If callbacks are passed to child components as prop, these components may trigger additional rerendering. In these scenarios, for performance reasons, the best choice is to use.bind() or the class’s public field syntax.

5. How do I pass parameters to event handlers or callbacks?

You can use an arrow function to wrap an event handler and pass arguments:

<button onClick={() = > this.handleClick(id)} />
Copy the code

This is equivalent to calling the.bind function:

<button onClick={this.handleClick.bind(this, id)} />
Copy the code

In addition to these two methods, you can also pass arguments to an arrow function:

<button onClick={this.handleClick(id)} />;
handleClick = id= > () = > {
  console.log('Hello, your ticket number is', id);
};
Copy the code

6. What are synthetic events in React?

SyntheticEvent is a cross-browser wrapper based on browser-native events. It has the same API as the browser’s native events, including stopPropagation() and preventDefault(), but the event behaves the same across all browsers.

7. What are inline conditional expressions?

You can conditionally render an expression using any of the IF statements or ternary expressions available to JS. In addition to these methods, you can embed any expression in JSX by enclosing all expressions in curly braces followed by the JS logical operator &&.

<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

Is whatkeyProp? What are the benefits of using it in an array of elements?

Key is a special string attribute that you should include when you create an array of elements. The Key prop helps React identify which items were changed, added, or removed.

In general, we use the ID in the data as the key:

const todoItems = todos.map(todo= > <li key={todo.id}>{todo.text}</li>);
Copy the code

If the rendered item does not have a stable ID, the next best thing is to use index as the key:

const todoItems = todos.map((todo, index) = > <li key={index.toString()}>{todo.text}</li>);
Copy the code

Note:

  1. It is not recommended if the list item may changeindexesAs akeys. This can have a negative impact on performance and can lead to problems with component state.
  2. If you extract a list item as a separate component, apply it on the list componentkeysRather thanliThe label.
  3. If the list item does not existkeyProp, a warning message will appear on the console.

9. What are refs for?

Refs is used to return a reference to the element. In most cases, they should be avoided, but they can be useful when you need direct access to instances of DOM elements or components.

10. How to create refs?

There are two ways to do this

1. This is a recently added method. Create the refs using the React.createref () method and attach it to the React element via the ref attribute. To use refs throughout the component, you simply assign the ref to the instance property in the constructor.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />; }}Copy the code
  1. You can use the ref callback method regardless of the React version. For example, the input element of the search bar component is accessed 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

You can also use refs in function components using closures.

Note: You can also use inline ref callbacks, even though this is not recommended