最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - duplicate component onclick React - Stack Overflow

programmeradmin0浏览0评论

I"m new to react, I'm creating a registration from. I want the user to be able to click a button to add an additional person to the registration. I have a "person" ponent which holds the form fields, onclick I want to duplicate that ponent.

import React, { useRef } from 'react'
import Person from './Person'

function BookingForm() {
    const registrationForm = useRef()
    console.log(registrationForm.current)
    let handleAddPerson = (e) => {
        e.preventDefault()
        registrationForm.appendChild(<Person/>)
    }
    
    return (
        <>
        <form ref={registrationForm} id='registrationForm'>
            <Person/>
            <button onClick={handleAddPerson}  className="btn btn-main mt-2"><i className="fas fa-plus"></i> ADD PERSON</button>
        </form>
        </>
    )
}

export default BookingForm

I"m new to react, I'm creating a registration from. I want the user to be able to click a button to add an additional person to the registration. I have a "person" ponent which holds the form fields, onclick I want to duplicate that ponent.

import React, { useRef } from 'react'
import Person from './Person'

function BookingForm() {
    const registrationForm = useRef()
    console.log(registrationForm.current)
    let handleAddPerson = (e) => {
        e.preventDefault()
        registrationForm.appendChild(<Person/>)
    }
    
    return (
        <>
        <form ref={registrationForm} id='registrationForm'>
            <Person/>
            <button onClick={handleAddPerson}  className="btn btn-main mt-2"><i className="fas fa-plus"></i> ADD PERSON</button>
        </form>
        </>
    )
}

export default BookingForm

Share Improve this question asked Jan 22, 2022 at 3:20 JuliusJulius 731 silver badge6 bronze badges 1
  • Can you share the person ponent code ! – Mayur Vaghasiya Commented Jan 22, 2022 at 4:23
Add a ment  | 

1 Answer 1

Reset to default 10

I would like to remend you implement it using state instead of ref. Like below:

import React, { useState } from 'react'
import Person from './Person'

function BookingForm() {
    const [persons,setPerson] = useState([<Person key={0} />]);

    let handleAddPerson = (e) => {
        e.preventDefault()
        setPerson([...persons,<Person key={persons.length} />]);
    }
    
    return (
        <>
        <form id='registrationForm'>
            {persons}
            <button onClick={handleAddPerson}  className="btn btn-main mt-2"><i className="fas fa-plus"></i> ADD PERSON</button>
        </form>
        </>
    )
}

export default BookingForm;

Hope this will help you. Using state is better in this case.

发布评论

评论列表(0)

  1. 暂无评论