阅读 343

React技巧:props.children

前言: 写一篇试试看吧, 平时开发积累小技巧。持续更新~

##场景:(一个具体实例,多种实现方式。)React 常用的this.props.children,当children需要使用父组件props

1.React.cloneElemnt

const { children, ...rest } = this.props;
    let renderHtml;
    renderHtml = Children.map(children, (element, i) => {
      return isValidElement(element) && cloneElement(element, { rest, key: i })
    })
    return renderHtml
复制代码
  1. 手动集成props, 子组件固定为Child
const { children, ...rest } = this.props;
Children.map((Component, index) => {
			// 当前child props
            const { props = {}, } = Component;
            const { id } = props;
            const newProps = {
              ...rest, // 父级props
              ...props
            }
            return <Child key={id} {...newProps} />
          })
复制代码
  1. 传统方式Context,可以用高阶函数封装
export const context = React.createContext({});
export const ProviderParent = {
const { children, closeBtn, ...rest } = props;
const { Provider } = context;
  return (
 	<div>
        <div>
          <Provider value={rest}>
            {children}
          </Provider>
          {closeBtn && <i className={style.closeIcon} onClick={props.onClose} />}
        </div>
      </div>
    </div>
  )}

// 创建consumerHoc
export function consumerContext(WrappedComponent) {

  return class Enhancer extends Component {
  
    render() {
      const {Consumer} =modalContext;
      return (
      <Consumer>{value =>
        <WrappedComponent {...value} {...this.props} />}</Consumer>
      )
    }
  }
}

// Child 子组件
const Child = (props) => (
  <div>
    child组件{props}
  </div>
)

export default consumerContext(Child)
复制代码

小女子水平有限, 感谢您的宝贵时间。 欢迎指正~

文章分类
阅读
文章标签