这是一篇给 react 新手的文章,老鸟就略过吧 ✈️作者:Llorenç Muntaner原文:https://medium.com/javascript…作为一名编程教师,我见过许多学生尝试这样做: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 arrayReact.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 方法了!