React组件对子组件children进行加强的方法

2022-01-11,,,,

这篇文章主要给大家介绍了关于React组件对子组件children进行加强的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用React具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧

问题

如何对组件的children进行加强,如:添加属性、绑定事件,而不是使用{this.props.children}在上进行处理。

前车之鉴

今天写组件遇到这个问题,在网上查阅了很多资料,都说可以使用React.cloneElement进行处理,但是结果并不是预期想要的。

先看看这个东西有什么用:

 React.cloneElement(element, [props], [...childrn])

根据React官网的说法,以上代码等价于:

 {children}

这么做其实也是给children包了一层标签,再对其进行间接处理,没有直接修改children。

如:

 // App.jsx   console.log('hello')}> demo 

我们希望在Father.jsx的内部将div转为inline-block。按照网上的做法,是这样的:

 // Father.jsx const Son = React.cloneElement( this.props.children, { style: { display: 'inline-block' } } )

但是实际效果是这样的:

   console.log('hello')}> demo 

哈!?子元素的父元素被设为了inline-block,和我们想要的demo被设为inline-block。结果与预期完全不同,简直大失所望!!!

React.clone根本对不起它clone的名字!!!

自我探索

思路: jsx语法表示的元素只是react组件的一个语法糖。所以组件是对象。既然是对象我们就可以直接对其进行修改。

尝试在控制台打印一个如下react组件:

 // this.props.children console.log(  { console.log('hello'); }} > demo  );

如下:

所以直接修改this.props.children即可:

 // Father.jsx const { children } = this.props; const Son = { ...children, props: { ...children.props, dispaly: { ...children.style, display: 'inline-block' }, onTransitionEnd: () => { console.log('hello world') } } }

总结

如何对组件的children进行直接加强,直接修改this.props.children对象即可。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对本站的支持。

以上就是React组件对子组件children进行加强的方法的详细内容,更多请关注本站其它相关文章!

《React组件对子组件children进行加强的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。