前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[译]你会在 JSX 里 console.log 吗

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

作者头像
JS菌
发布2019-04-10 15:26:45
4240
发布2019-04-10 15:26:45
举报
文章被收录于专栏:JS菌JS菌

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

  • 作者:Llorenç Muntaner
  • 原文:https://medium.com/javascript-in-plain-english/can-you-console-log-in-jsx-732f2ad46fe1

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

1render() {
2  return (
3    <div>
4      <h1>List of todos</h1>
5      console.log(this.props.todos)
6    </div>
7  );
8}

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

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

最常用的解决方案:

在JSX中嵌入表达式:

1render() {
2  return (
3    <div>
4      <h1>List of todos</h1>
5      { console.log(this.props.todos) }
6    </div>
7  );
8}

另一种流行的解决方案:

console.log 放在 return() 前面

1render() {
2  console.log(this.props.todos);
3  return (
4    <div>
5      <h1>List of todos</h1>
6    </div>
7  );
8}

一种奇特的解决方案:

直接写一个 <ConsoleLog> 组件

1const ConsoleLog = ({ children }) => {
2  console.log(children);
3  return false;
4};

使用方法:

1render() {
2  return (
3    <div>
4      <h1>List of todos</h1>
5      <ConsoleLog>{ this.props.todos }</ConsoleLog>
6    </div>
7  );
8}

为什么要这样做?

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

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

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

1const element = (
2  <h1 className="greeting">
3    Hello, world!
4  </h1>
5);

他会被编译成下面这样:

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

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

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

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

1<div>
2  <h1>List of todos</h1>
3  console.log(this.props.todos)
4</div>
5

将被编译成:

 1// when more than 1 thing is passed in, it is converted to an array
 2React.createElement(
 3  'div',
 4  {}, // no props are passed/
 5  [ 
 6    React.createElement(
 7      'h1',
 8      {}, // no props here either
 9      'List of todos',
10    ),
11    'console.log(this.props.todos)'
12  ]
13);

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

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

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

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

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-03-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 JS菌 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 最常用的解决方案:
  • 另一种流行的解决方案:
  • 一种奇特的解决方案:
  • 为什么要这样做?
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档