当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React组件对子组件children进行加强的方法

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

问题

如何对组件的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对象即可。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网