我试图找到正确的方法来定义一些组件,这些组件可以以通用的方式使用:

<Parent>
  <Child value="1">
  <Child value="2">
</Parent>

当然,在父组件和子组件之间呈现有一个逻辑,您可以想象<select>和<option>是这个逻辑的一个例子。

这是为了解决这个问题的一个虚拟实现:

var Parent = React.createClass({
  doSomething: function(value) {
  },
  render: function() {
    return (<div>{this.props.children}</div>);
  }
});

var Child = React.createClass({
  onClick: function() {
    this.props.doSomething(this.props.value); // doSomething is undefined
  },
  render: function() {
    return (<div onClick={this.onClick}></div>);
  }
});

问题是无论何时使用{this.props。Children}定义一个包装器组件,如何将某些属性传递给它的所有子组件?


当前回答

方法一——克隆儿童

const Parent = (props) => {
   const attributeToAddOrReplace= "Some Value"
   const childrenWithAdjustedProps = React.Children.map(props.children, child =>
      React.cloneElement(child, { attributeToAddOrReplace})
   );

   return <div>{childrenWithAdjustedProps }</div>
}

完整的演示

方法2 -使用可组合的上下文

上下文允许您将道具传递给深度子组件,而无需显式地将其作为道具传递给中间的组件。

环境也有缺点:

数据不会以常规的方式流动——通过道具。 使用上下文将在使用者和提供者之间创建契约。理解和复制重用组件所需的需求可能会更加困难。

使用可组合的上下文

export const Context = createContext<any>(null);

export const ComposableContext = ({ children, ...otherProps }:{children:ReactNode, [x:string]:any}) => {
    const context = useContext(Context)
    return(
      <Context.Provider {...context} value={{...context, ...otherProps}}>{children}</Context.Provider>
    );
}

function App() {
  return (
      <Provider1>
            <Provider2> 
                <Displayer />
            </Provider2>
      </Provider1>
  );
}

const Provider1 =({children}:{children:ReactNode}) => (
    <ComposableContext greeting="Hello">{children}</ComposableContext>
)

const Provider2 =({children}:{children:ReactNode}) => (
    <ComposableContext name="world">{children}</ComposableContext>
)

const Displayer = () => {
  const context = useContext(Context);
  return <div>{context.greeting}, {context.name}</div>;
};

其他回答

从上面所有的答案中得到启发,这就是我所做的。我传递一些道具,比如一些数据和一些组件。

import React from "react";

const Parent = ({ children }) => {
  const { setCheckoutData } = actions.shop;
  const { Input, FieldError } = libraries.theme.components.forms;

  const onSubmit = (data) => {
    setCheckoutData(data);
  };

  const childrenWithProps = React.Children.map(
    children,
    (child) =>
      React.cloneElement(child, {
        Input: Input,
        FieldError: FieldError,
        onSubmit: onSubmit,
      })
  );

  return <>{childrenWithProps}</>;
};

在我的情况下,React.cloneElement()给了我很多问题,我使用Typescript的函数组件,所以我用孩子(道具)作为一种方式来传递我的道具给我的孩子元素。同样,我的情况非常独特,我必须传递给父组件一个属性,然后基于该属性,它将某些道具传递给子组件。这可以在一个简单的CodeSandbox示例中看到

App.tsx

import "./styles.css";
import Parent from "./Parent";

export default function App() {
  return (
    <>
      <Parent title={"With div wrapper"}>
        {({ title }) => <h1>{title}</h1>}
      </Parent>

      <Parent>
        {({ title }) => <h1>{title === undefined && "this is undefined"}</h1>}
      </Parent>
    </>
  );
}

Parent.tsx

export interface ChildrenProps {
  title?: string;
}

interface ParentWrapperProps {
  children: (title: ChildrenProps) => JSX.Element;
  title?: string;
}

const ParentWrapper: React.FC<ParentWrapperProps> = ({ children, title }) => {
  return title ? (
    <div>{children({ title: title })}</div>
  ) : (
    <>{children({ title: undefined })}</>
  );
};

export default ParentWrapper;

根据cloneElement()的文档

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

克隆并返回一个新的React元素,使用element作为起始元素 点。生成的元素将具有原始元素的道具 新道具浅浅地融合在一起。新的孩子将取代 现有的儿童。原元素的Key和ref将为 保存了下来。 React.cloneElement()几乎等同于: <元素。{…元素类型。道具道具}{…}>{孩子}< / element.type > 然而,它也保留了裁判。这意味着如果你有了孩子 有裁判在上面,你就不会不小心从你的祖先那里偷了它。 你会得到相同的引用附加到你的新元素。

因此,您将使用cloneElement为儿童提供自定义道具。然而,组件中可能有多个子组件,您需要循环遍历它。其他答案建议你使用react。children。map来映射它们。然而React. children .map不同于React。cloneElement更改Element附加项和额外的。$作为前缀的键值。查看这个问题了解更多细节:React。React.Children.map中的cloneElement会导致元素键的改变

如果您希望避免它,您应该改用forEach函数,如

render() {
    const newElements = [];
    React.Children.forEach(this.props.children, 
              child => newElements.push(
                 React.cloneElement(
                   child, 
                   {...this.props, ...customProps}
                )
              )
    )
    return (
        <div>{newElements}</div>
    )

}

渲染道具是解决这个问题最准确的方法。不要将子组件作为子道具传递给父组件,而是让父组件手动呈现子组件。渲染是react中的内置道具,它接受函数参数。在这个函数中,你可以让父组件用自定义参数呈现你想要的任何东西。基本上,它做的事情与子道具相同,但它更可定制。

class Child extends React.Component {
  render() {
    return <div className="Child">
      Child
      <p onClick={this.props.doSomething}>Click me</p>
           {this.props.a}
    </div>;
  }
}

class Parent extends React.Component {
  doSomething(){
   alert("Parent talks"); 
  }

  render() {
    return <div className="Parent">
      Parent
      {this.props.render({
        anythingToPassChildren:1, 
        doSomething: this.doSomething})}
    </div>;
  }
}

class Application extends React.Component {
  render() {
    return <div>
      <Parent render={
          props => <Child {...props} />
        }/>
    </div>;
  }
}

在codepen的例子

你不再需要{this.props.children}。现在你可以在Route中使用render来包装你的子组件,并像往常一样传递你的道具:

<BrowserRouter>
  <div>
    <ul>
      <li><Link to="/">Home</Link></li>
      <li><Link to="/posts">Posts</Link></li>
      <li><Link to="/about">About</Link></li>
    </ul>

    <hr/>

    <Route path="/" exact component={Home} />
    <Route path="/posts" render={() => (
      <Posts
        value1={1}
        value2={2}
        data={this.state.data}
      />
    )} />
    <Route path="/about" component={About} />
  </div>
</BrowserRouter>