[译]你会在 JSX 里 console.log 吗

栏目: JavaScript · 发布时间: 6年前

内容简介:这是一篇给 react 新手的文章,老鸟就略过吧 :airplane:作为一名编程教师,我见过许多学生尝试这样做:

[译]你会在 JSX 里 console.log 吗

这是一篇给 react 新手的文章,老鸟就略过吧 :airplane:

作为一名编程教师,我见过许多学生尝试这样做:

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

这不会在控制台中打印预期的列表。它只会在浏览器中渲染一个字符串 console.log(this.props.todos)

我们先来看看一些非常简单的解决方案,然后我们将解释原因。

最常用的解决方案:

在JSX中嵌入表达式:

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

另一种流行的解决方案:

console.log 放在 return() 前面

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

一种奇特的解决方案:

直接写一个 <ConsoleLog> 组件

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

使用方法:

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

为什么要这样做?

我们需要记住 JSX 并不是普通的 JavaScript,也不是 HTML,而是一种语法扩展。

最终 JSX 会被编译成普通的 JavaScript

比方说,我们写一段如下 JSX 代码:

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

他会被编译成下面这样:

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

我们先来回顾一下 React.createElement 的几个参数:

  • h1 : 这个是一个字符串代表的是标签名
  • { className: 'greeting' } 这是标签 h1 使用的 props 这将会被转换为对象。对象的键就是 prop 的名称,值就是该属性的值
  • Hello, world! 则是 children,字符串将被插入进 <h1></h1> 之间

现在让我们回顾一下我们在本文开头尝试编写的失败的 console.log

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

将被编译成:

// when more than 1 thing is passed in, it is converted to an array
React.createElement(
  'div',
  {}, // no props are passed/
  [ 
    React.createElement(
      'h1',
      {}, // no props here either
      'List of todos',
    ),
    'console.log(this.props.todos)'
  ]
);

我们看到 console.log 被认为是一个字符串,插入到 createElement 方法中去。这段代码并没有被执行

这是有道理的,看我们代码上头有个 h1 标签,代表着 title 。那么计算机是如何知道哪些字符串需要被执行,哪些是需要被直接渲染的呢?

答案是:它认为两者都是一个字符串。在任何时候,它始终将文本视为字符串。

因此,如果您希望执行该操作,则需要指定JSX来执行此操作。通过将其作为表达式嵌入 {}

就是这样,好了现在你知道应该在什么地方、什么时候以及如何去在 JSX 中调用 console.log 方法了!

[译]你会在 JSX 里 console.log 吗


以上所述就是小编给大家介绍的《[译]你会在 JSX 里 console.log 吗》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

A Guide to Monte Carlo Simulations in Statistical Physics

A Guide to Monte Carlo Simulations in Statistical Physics

Landau, David P./ Binder, Kurt / Cambridge Univ Pr / 2005-9 / 786.00元

This new and updated edition deals with all aspects of Monte Carlo simulation of complex physical systems encountered in condensed-matter physics, statistical mechanics, and related fields. After brie......一起来看看 《A Guide to Monte Carlo Simulations in Statistical Physics》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具