zoukankan      html  css  js  c++  java
  • React组件中对子组件children进行加强

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

    问题

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

  • 相关阅读:
    Leetcode: Surrounded Regions
    Leetcode: 3Sum Closest
    Leetcode: 3Sum
    Leetcode: Wildcard Matching
    Leetcode: Edit Distance
    Leetcode: Best Time to Buy and Sell Stock III
    Leetcode: Combination Sum II
    Leetcode: Next Permutation
    Leetcode: Merge Intervals
    Leetcode: Minimum Window Substring
  • 原文地址:https://www.cnblogs.com/looyulong/p/11071367.html
Copyright © 2011-2022 走看看