likes
comments
collection
share

React中的renderProps和childrenProps

作者站长头像
站长
· 阅读数 27

一:废话不多说,直接开讲:

React中的renderProps和childrenProps

这里有三个组件,我想让B组件内展示C组件,也就是说我想让B组件成为C组件的父亲。(这不是废话吗)我这样写不就完事了吗?

React中的renderProps和childrenProps

但是实际工作当中,我们经常会暂时不太确定B,C组件的关系,等到最后的时候再决定,这时候我们假设B组件最后肯定是C组件的父组件。

其实React中还有第二种让C组件成为B组件子元素的方法。

你如果之前学过提前学过一些知识点话,你对这个肯定不陌生,也就是B标签的标签体内容是C标签。

React中的renderProps和childrenProps

但是如果你单纯这样写的话,很遗憾,页面上是不会显示C标签的

React中的renderProps和childrenProps

你可能会奇怪,不应该啊,这咋回事啊。

注意重点来了: 这时候你把B的爸爸忽略了吧?A标签说:你小子在我屁股底下蹦跶不管我了是吧?这时候你其实是在A标签传递给B标签的props的children属性中写内容,你爸爸给你东西,你不收也没办法展示啊,对吧?

React中的renderProps和childrenProps

React中的renderProps和childrenProps

ok,页面现在正常显示了

二:renderprops

现在展示是展示了,但是,客户需求突然变了,想让你的B标签想给C标签一个属性,叫做name,值为"方"让它在C标签中展示,这咋办呢?

你可能会想,这不就是简简单单的父亲向儿子传递数据吗?props不就完事了吗?你于是兴高采烈的打开代码,然后找到B标签

React中的renderProps和childrenProps

奇怪,我的C标签呢?哦,对 在A标签里,我得这样写!

React中的renderProps和childrenProps

当你刚刚敲下name的时候就发现了,state是B标签的,A标签压根就没有!!

这怎么办呢?

React中的renderProps和childrenProps

没办法,你只能修改你的代码为这样,给B一个属性,属性值为函数,并且返回值为C标签。然后咋办?在B标签里调呗!

React中的renderProps和childrenProps

调用的时候,把name值放进参数里,然后在返回的C标签内直接使用,如下图:

React中的renderProps和childrenProps

最后一步别忘了,你C标签还没接收呢!

React中的renderProps和childrenProps

页面效果,成功显示~

React中的renderProps和childrenProps

非得叫render吗?不需要,你可以随便起名字,只不过是程序员之间的一种约定,当你写render的时候,别人看你的代码会马上知道你行代码的意思。就好比for循环里写i=0,那样互相约定俗称的规矩。

补充一下拓展知识

React中的renderProps和childrenProps

B组件里加文字,也相当于props,需要你在B组件内部接收才可以使用!