The introduction

As a beginner to React, you will often write the following code:

render() {
  return (
    <div>
      <h1>List of todos</h1>
      console.log(this.props.todos)
    </div>
  );
Copy the code

This will not print the toDOS message you expect on the console, it will just render the string console.log(this.props. Todos) in the browser.

The solution

The most commonly used scheme

Embed expressions in your JSX code:

render() {
  return (
    <div>
      <h1>List of todos</h1>
      { console.log(this.props.todos) }
    </div>
  );
}
Copy the code

Another popular option

Place your console.log before return() :

render() {
  console.log(this.props.todos);
  return (
    <div>
      <h1>List of todos</h1>
    </div>
  );
}
Copy the code

Novel scheme

We can certainly customize a

component:

const ConsoleLog = ({ children }) = > {
  console.log(children);
  return false;
};
Copy the code

Then import this component as needed:

render() {
  return (
    <div>
      <h1>List of todos</h1>
      <ConsoleLog>{ this.props.todos }</ConsoleLog>
    </div>
  );
}
Copy the code

How to explain all this

First of all, JSX is not native JavaScript, nor is it HTML, it is an extension language.

Extended languages refer to the languages that need to be compiled before being executed by the browser. For example, we are familiar with the style preprocessor: Sass. The style files written in this language, with the suffix.scss, are processed by sass-Loader in Webpack and finally converted into.css files that can be understood by the browser

Similarly,.jsx will eventually be compiled to native.js. For example 🌰, we write in JSX:

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);
Copy the code

It will eventually compile to:

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world! '
);
Copy the code

Babel (the next generation JavaScript compiler) is behind all of this, so you can open Babel/repl and try it out for yourself.

What does each parameter to the React.createElement represent?

  • 'h1': The label name, which is a string
  • { className: 'greeting' }Will:<h1>Properties to objects, such as className, event handler, props
  • 'Hello, world! ': to be calledchildren, including<h1>All child content within the tag

Let’s turn to the code at the beginning of the article:

<div>
  <h1>List of todos</h1>
  console.log(this.props.todos)
</div>
Copy the code

Will eventually compile to:

// Children are treated as an array when multiple children are included'div', {}, // No attribute [react. createElement(// when new tag h1 is encountered, execute react. createElement again'h1', {}, // Again no attributes'List of todos',),'console.log(this.props.todos)']);Copy the code

At the end

When you want to useconsole.logSimply embed the code into{} 中

Can you console.log in JSX?