简体   繁体   中英

How to show a div when a button is clicked

I just want to know, how to show a anything in a HTML body when the button is clicked. Is there anythin like echo in php

this is my appTodo.js code....

import React, { useState } from 'react'

export default function AddTodo() {
    
    const [input, setInput] = useState("");
    
    const onChange = (e) => {
        setInput(e.target.value)
    }

    const handleOnClick = () => {
        console.log(input)
        setInput("")
    }

    return (
        <div className='container my-3 col-6'>
            <form>
                <input className="form-control" onChange={onChange} type="text" placeholder="What to do?" value={input} />
                <button id='addbtn' onClick={handleOnClick} type="button" className="btn btn-dark my-3">Add</button>
            </form>
        </div>
    )
}

Just you need to create one variable to keep the state of the visibility of the div.

import React, { useState } from 'react'

export default function AddTodo() {
const [input, setInput] = useState("");
const [divVisibility, setDivVisibility] = useState(false);



const onChange = (e) => {
    setInput(e.target.value)
}

const handleOnClick = () => {
    setInput("")
    setDivVisibility(true)
}

return (
    <div className='container my-3 col-6'>
        <form>
            <input className="form-control" onChange={onChange} type="text" placeholder="What to do?" value={input} />
            <button id='addbtn' onClick={handleOnClick} type="button" className="btn btn-dark my-3">Add</button>
        </form>
        
    {divVisibility && 
      <div>
        Your content
      </div>
    }
    </div>


)
}


This code makes a state that can be changes between true and false by clicking the button. When false "componenet" = null, and when true "component" = (your component).

const [visible, setVisible] = useState(false);

function makeVisible() {
  if(visible === false){
    setVisible(true)
  } else setVisible(false);
}

const component = visible == true ? <h1>SHOWN</h1> : null;
const buttonString = visible == true? "UnShow" : "Show"

  return (
    <div className="App">
      <h1>Hello World!</h1>
      {component}
      <button onClick={makeVisible} >{buttonString}</button>
    </div>
  );
}

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