简体   繁体   中英

Text input field won't submit when pressing enter

I have a text input that I am trying to use to create new tags via hooks. However, when I enter in the value and press enter, nothing happens. I Googled it and was told to make the input type=text but this has not fixed it. Here is the code:

 import React, { useState } from 'react'; import AddIcon from '@mui/icons-material/Add'; import MaximizeIcon from '@mui/icons-material/Maximize'; import './styles.css'; const Card = ({ id, pic, name, email, company, skill, average, grades }) => { const [clicked, setClicked] = useState(false); const [tags, setTags] = useState([]); return ( <div className='card' id={id}> <img src={pic} alt='avatar' className='img' /> <div className='list'> <h1>{name}</h1> <div className='properties'> <p>Email: {email}</p> <p>Company: {company}</p> <p>Skill: {skill}</p> <p>Average: {average}</p> </div> <input type='text' placeholder='Add a tag' onSubmit={(e) => { setTags(...tags, e.target.value); console.log(tags); }} /> {clicked && ( <div className='grades'> {grades.map((grade, index) => ( <p>{`Test ${index}: ${grade}%`}</p> ))} </div> )} </div> <button onClick={() => setClicked(!clicked)}> {!clicked ? ( <AddIcon fontSize='large' /> ) : ( <MaximizeIcon fontSize='large' /> )} </button> </div> ); }; export default Card;

How do I make it submit a new tags to the setTags hook?

You can use keyDown Event

onKeyDown = {
  (e) => {
    if (e.key === 'Enter') {
      setTags(...tags, e.target.value);

    }
  }
}

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