最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

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

来源:动视网 责编:小采 时间:2020-11-27 21:54:36
文档

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

React组件对子组件children进行加强的方法:问题 如何对组件的children进行加强,如:添加属性、绑定事件,而不是使用<div>{this.props.children}</div>在<div>上进行处理。 前车之鉴 今天写组件遇到这个问题,在网上查阅了很多资料,都说可以使用React.cloneEleme
推荐度:
导读React组件对子组件children进行加强的方法:问题 如何对组件的children进行加强,如:添加属性、绑定事件,而不是使用<div>{this.props.children}</div>在<div>上进行处理。 前车之鉴 今天写组件遇到这个问题,在网上查阅了很多资料,都说可以使用React.cloneEleme


问题

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

前车之鉴

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

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

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

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

<element.type {...element.props} {...props}>{children}</element.type>

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

如:

// App.jsx
<Father>
 <div style={{ color: 'red' }} onClick={() => console.log('hello')}>
 demo
 </div>
<Father>

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

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

但是实际效果是这样的:

<div style={{ dispaly: 'inline-block' }}>
 <div style={{ color: 'red' }} onClick={() => console.log('hello')}>
 demo
 </div>
<div>

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

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

自我探索

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

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

// this.props.children
console.log(
 <div
 style={{ color: 'red' }}
 onClick={() => {
 console.log('hello');
 }}
 >
 demo
 </div>
);

如下:

所以直接修改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进行加强的方法:问题 如何对组件的children进行加强,如:添加属性、绑定事件,而不是使用<div>{this.props.children}</div>在<div>上进行处理。 前车之鉴 今天写组件遇到这个问题,在网上查阅了很多资料,都说可以使用React.cloneEleme
推荐度:
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top