这是一篇给 react 新手的文章,老鸟就略过吧 ✈️
作为一名编程教师,我见过许多学生尝试这样做:
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
方法了!