在提交时不会触发ReactJs中的函数

dgiusagp  于 2023-02-15  发布在  React
关注(0)|答案(2)|浏览(184)
const CreateMessage = () => {
    const disatch = useDispatch()
    const chatR = useSelector(state => state.chat);
    const { chat } = chatR;
    const [text, setText] = useState("")
    useEffect(()=>{
        setText("")
    },[chat])
    
    function handleSubmit(event) {
        event.preventDefault()
        console.log(3333)
      }
    
  return (
    <StyledCreateMessage id="myform" onSubmit={handleSubmit}>
        <div className="searchForm">
            {/* <input className='input' type="text" placeholder='Write a message...' /> */}
            <textarea value={text} onChange={(e)=>setText(e.target.value)}  spellCheck="false" className='input' placeholder='write a message...'></textarea>
        </div>
        <div className="send">
        <Stack direction="row" spacing={1}>
                <IconButton  color="primary" sx={{color:"white"}} aria-label="upload picture" component="label">
                    <input hidden  type="file"  />
                    <AttachFileIcon />
                </IconButton>
                <IconButton  color="primary" sx={{color:"white"}} aria-label="upload picture" component="label">
                    <input hidden type="file" accept='image/*' />
                    <PhotoCamera />
                </IconButton>
                <IconButton type="submit" form="myform" color="primary" sx={{color:"white"}} aria-label="upload picture" component="label">
                    <SendIcon />
                </IconButton>
        </Stack>

        </div>
    </StyledCreateMessage>
  )
}

为什么当我计时的时候

<IconButton type="submit" form="myform" color="primary" sx={{color:"white"}} aria-label="upload picture" component="label">
   <SendIcon />
</IconButton>

它不会触发handleSubmit

l5tcr1uw

l5tcr1uw1#

您需要将onClick={handleSubmit}添加到图标按钮。
下面是一个来自react docs的例子:https://reactjs.org/docs/forms.html

jyztefdp

jyztefdp2#

窗体将不具有基于设置方式的按钮上下文。
你可以做几件事
1.按钮必须在窗体本身中,这似乎是您想要的。
1.执行上述onClick解决方案
1.在表单组件和按钮之间传递一些状态,这对于简单的事情来说似乎很困难。

相关问题