React组件中对子组件children进行增强

React组件中对子组件children进行增强

问题

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

前车可鉴

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

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

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

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

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

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

如:blog

// 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'
        }
    }
)

可是实际效果是这样的:element

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

哈!?子元素的父元素被设为了inline-block,和咱们想要的<div>demo</div>被设为inline-block。结果与预期彻底不一样,简直大失所望!!!jsx

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

自我探索

思路: 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对象便可。

相关文章
相关标签/搜索