简体   繁体   English

如何将自定义道具传递给道具?

[英]How to pass custom prop to a prop?

I am fairly new to react and this is a problem I am trying to solve.我对反应还很陌生,这是我正在努力解决的问题。

There is a parent component parent which passes props to the child.有一个父组件parent将 props 传递给子组件。 One of these props, include an element to be rendered like this:其中一个道具,包括一个要渲染的元素,如下所示:

<child componentToBeRendered = {component} />

In the child, I want to take this component and pass a prop to it, which is defined in the child itself.在子组件中,我想获取这个组件并将一个 prop 传递给它,它是在子组件本身中定义的。

function child(props){
    function toBePassed(){ ... }
    <props.componentToBeRendered fun = {toBePassed} />
}

I know that the above code is wrong and we cannot use <props.componentToBeRendered> .我知道上面的代码是错误的,我们不能使用<props.componentToBeRendered> So how can I pass a custom prop to this component?那么如何将自定义道具传递给这个组件呢?

The only way I can think of rendering the component is like: {props.componentToBeRendered};我能想到的渲染组件的唯一方法是: {props.componentToBeRendered};

How do I render this component with a custom prop defined in the child?如何使用子项中定义的自定义道具渲染此组件?

You can rename the passed component prop, render it as per usual, and pass props to it as per usual.您可以重命名传递的组件 prop,照常渲染它,并照常将 props 传递给它。 Similar to Choosing the Type as Runtime类似于选择类型作为运行时

function Child(props){
    const ComponentToBeRendered = props.componentToBeRendered;

    function toBePassed(){ ... }

    return <ComponentToBeRendered fun={toBePassed} />;
}

I've usually used this pattern with prop destructuring in the function signature, renaming the destructured prop.我通常在函数签名中使用这种模式与 prop 解构,重命名解构的 prop。

function Child({ componentToBeRendered: ComponentToBeRendered }) {
  function toBePassed(){ ... }

  return <ComponentToBeRendered fun={toBePassed} />;
}

You can use React's top-level API, specifically React.createElement , for instance:你可以使用 React 的顶级 API,特别是React.createElement ,例如:

const MyChild1 = ({ num }) => <div>num1: {num}</div>;
const Parent = ({ comp }) => 
  <div>
    {React.createElement(comp, { num: 5 })}
    {React.createElement(comp, { num: 1 })}
  </div>
;

I think you shouldn't pass the component as a prop Instead pass a value to the child that indicates the component to be rendered.我认为您不应该将组件作为道具传递,而是将一个值传递给指示要呈现的组件的子组件。

function Parent(){
   return <Child toBeRendered="contact"/>
}
function Child(props){
   let toBeRenderd;
   switch(props.toBeRendered){
      case 'contact' :
          toBeRendered = Contact;
      default :
          toBeRendered = Info
   }
   return <toBeRendered/>
}

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

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