简体   繁体   中英

React: I want to make a function that renders a new component with onClick EVERY TIME it's clicked

I'm creating a kanban board. I'm trying to create a button that adds a new card.

So far I've been able to create a conditional with states that will essentially toggle a card. It'll appear when clicked and disappear when the button is clicked again, which is not what I want so I started over.

This is the function I want to call onClick. The message logs in the console when the button is clicked but the KanBanCard component is unresponsive and there are no errors.

newCard() {
        console.log("New card being displayed");

        return (
            <div>
                <KanBanCard />
            </div>
        )

    }

My button rendering:

return (
            <main>
                <button onClick={this.newCard} className="card-add">
                    +
                </button>
            </main>
            
        )

It's not rendering because you are not rendering the new <KanBanCard /> that you are creating. You cannot return it because it will return it to the onClick method. What you can do is create a state that holds the list of Kanban cards and update that when the button is clicked. Make sure you render that list. It would look like this:

class YourComponent extends React.Component {
    constructor() {
        this.state = {
            kanbanList: [],
        }
    }

    newCard() {
        const newCard = <div><KanBanCard /></div>;
        this.setState({ kanbanList: [...this.state.kanbanList, newCard] });
    }

    render() {

        return (
            <main>
                <button onClick={this.newCard} className="card-add">+</button>
                <div className="cards-holder">
                    {this.state.kanbanList.map(card => card)}
                </div>
            </main>
        );
    }
}

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