关于入门实例中this.props的一个问题

#1

代码
如链接中的代码所示,JSX第14行如果不写{this.props.children}这个组件内容就不能正常显示,我不是很理解这里为什么要这么写。在我理解中,render()方法里面的是定义组件对象,this.props.children获取的是对象子节点。我刚刚开始学react,对内部机制不是很熟悉,求解答或者告诉我哪里可以找到相关资料

#2

this.props.children 代表的是 26、27 行的

  {todoItem.text}
  {console.log(todoItem.text)}

也就是这个例子里唯一的数据

最终形成的 html 大概如下(保留了数据原型)

<div className="todoList">
  <div className='todoItem' >
    {todoItem.text}
    {console.log(todoItem.text)}
    <div className="del"></div>
  <div className='todoItem' >
    {todoItem.text}
    {console.log(todoItem.text)}
    <div className="del"></div>
  </div>
</div>
1 Like
#4

好像点错了没有直接回复你,把评论写在三楼里了,重新发一次:
嗯,我之前写的时候,在定义组件的过程中没有{this.props.children}的情况下,控制台输出的现实是正常的。随意就认为26、7行是类似于实例化的过程,实例化的过程中再插入的数据在定义类的时候不做操作({this.props.children}这行)也可以。但是实际上没有{this.props.children}的情况下用{todoItem.text}插入js值却不能正常显示,还是不是很明白这样写的内部逻辑。{this.props.children}给我的感觉像是绑定数据值的锚点,不知道这么理解对不对

#5

this.props.children 只是传入 TodoItem 这个组件(或者说是函数)的参数。
参数嘛,在传入时,会先被求值。如 console.log(...) 会先被执行(所以,控制台会显示)。
当然啊,传入的参数你可以不用。不用自然不会显示啊。

1 Like
#6

多谢解答:)

#7

多谢解答:slight_smile: