简体   繁体   中英

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. Is it possible that I put the Submit component inside the Form component?

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

Submit.js

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

Quiz.js

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

You can use the children prop to achieve this.

Basically, in your Form.js, use props.children

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

Then in your Quiz.js , use it like this.

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

The <Submit /> component will now be rendered inside your Form component

Yes, you need add argument 'props' to form component and output on display {props.children}:

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

CodeSanbox demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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