简体   繁体   English

是否可以将组件放入组件中?

[英]Is it possible to put a component inside a component?

I have made a Form component which I want to reuse, I have also made an Submit component which I want to reuse.我制作了一个我想重用的Form组件,我还制作了一个我想重用的Submit组件。 Is it possible that I put the Submit component inside the Form component?是否可以将Submit组件放在Form组件中?

export const Form = () => {
    return (
        <form>
            
        </form>
    )
}

Submit.js提交.js

export const Submit = () => {
    return (
        <>
           <input type="submit">
        </>
    )
}

Quiz.js测验.js

export const Quiz = () => {
    return (
        <Form>
            <Submit>
        </Form>
    )
}

You can use the children prop to achieve this.您可以使用children道具来实现这一点。

Basically, in your Form.js, use props.children基本上,在您的 Form.js 中,使用props.children

export const Form = (props) => {
    return (
        <form>
            {props.children}
        </form>
    )
}

Then in your Quiz.js , use it like this.然后在您的Quiz.js中,像这样使用它。

export const Quiz = () => {
    return (
        <Form>
           <Submit />
        </Form>
    )
}

The <Submit /> component will now be rendered inside your Form component <Submit />组件现在将在您的Form组件中呈现

Yes, you need add argument 'props' to form component and output on display {props.children}:是的,您需要在显示 {props.children} 上添加参数“props”以形成组件和 output:

const Form = (props) => {
  return (
      <form>
          {props.children}
      </form>
  )
}

CodeSanbox demo CodeSanbox 演示

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

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