简体   繁体   English

如何将 {props.children} 添加到 React 组件

[英]How to add {props.children} to a React component

i have many components which have {props.children} deeply nested inside.我有很多组件,里面有很深的嵌套{props.children} considery DRY principle is there a way to add this using some React pattern.考虑 DRY 原则有没有办法使用一些 React 模式来添加它。

example let's say i have two components,例如,假设我有两个组件,

Comp1.js Comp1.js

import React from "react";

const Comp1 = props => {
  return (
    <div>
      <h1>{props.children}</h1>
    </div>
  );
};

export default Comp1;

Comp2.js Comp2.js

import React from "react";

const Comp2 = props => {
  return (
    <div>
      <div>
        <h1>{props.children}</h1>
      </div>
    </div>
  );
};

export default Comp2;

if you see above code we have both Comp1 and Comp2 have line of code {props.children} repeated inside.如果你看到上面的代码,我们有COMP1组合物2都有代码{} props.children线内重复。

what i want now is some function which will add this line of code, something like below,我现在想要的是一些将添加这行代码的函数,如下所示,

    const addPropsChildrenToComp  = (Comp)=>{
      return(
        (props)=>{
///do somehting here
        }
      )
    }


const Comp1 = props => {
  return (
    <div>
      <h1></h1>
    </div>
  );
};

Comp1WithPropsChildren = addPropsChildrenToComp(Comp1)

using HOC doesn't work because, in HOC we never modify passed component.使用 HOC 不起作用,因为在 HOC 中我们从不修改传递的组件。 anyway to aceve this.?反正要aceve这个。?

to get more idea of my problem see this demo: https://codesandbox.io/s/trusting-http-pd1yu要更多地了解我的问题,请参阅此演示: https : //codesandbox.io/s/trusting-http-pd1yu

in there i woul like to see CompWithPropsChildren component render props.children inside it.在那里,我希望看到 CompWithPropsChildren 组件在其中渲染 props.children。

I think I see what you're trying to get to, and you can accomplish this just using another component.我想我明白您想要达到的目标,您只需使用另一个组件即可完成此任务。

import React from "react";
import ChildComp from "./ChildComp";

const Comp1 = props => {
  return (
    <div>
      <ChildComp {...props} />
    </div>
  );
};

export default Comp1;
import React from "react";

const ChildComp = props => {
   return <h1>{props.children}</h1>
}

Assuming your ChildComp has some complex logic you don't want to duplicate, this will make it reusable for you.假设您的ChildComp有一些您不想复制的复杂逻辑,这将使您可以重用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM