【问题标题】:Button Breaks React Form按钮中断反应形式
【发布时间】:2020-12-20 02:03:12
【问题描述】:

我想在表单中添加按钮以动态添加输入。然而我发现,如果我在我的表单中添加一个按钮,它只是登录到控制台,(当我尝试添加输入时)它会记录下来,然后表单就会中断。我的 Electron 应用程序的前端窗口崩溃(不退出但变成灰色)并在同一页面上自动重新启动,而没有打开包含表单的对话框。

这是我的表单代码的 sn-p:

TaskCreation.js

return (
        <div className="modal-body">
            {values.products.map((product, i) => {
                return(
                    <div key={i}>
                <Form.Row>
                    <Form.Group as={Col} controlId={"keywords-" + i}>
                        <Form.Label>Keywords (e.g. '+box +logo +tee')</Form.Label>

                        <Form.Control
                            value={product.keywords.join(' ')}
                            onChange={handleChange}
                        >
                        </Form.Control>
                    </Form.Group>
                </Form.Row>
...

            <div style={{ marginTop:'10px' }}>
                <button onClick={() => console.log(123)}>Add Product</button> // this breaks when clicked
            </div>
...
);

欢迎任何帮助,让我知道我应该提供哪些其他信息。

【问题讨论】:

    标签: javascript reactjs forms electron jsx


    【解决方案1】:

    我认为该按钮会激活表单中的“提交”。所以,你可以尝试一些东西。将属性 type="button" 添加到您的按钮,和/或使用“.preventDefault()”。

    const handleButton = (event) => {
      event.preventDefault()
      console.log(123)
    }
    
    <div style={{ marginTop:'10px' }}>
      <button type="button" onClick={handleButton}>Add Product</button> 
    </div>
    

    【讨论】:

    • 谢谢丹尼尔!你能解释一下为什么我没有设置按钮的类型时它不起作用吗?是否默认提交?
    • 没错!什么时候是表单按钮,默认他的类型是提交
    猜你喜欢
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 2020-06-29
    • 2021-01-01
    • 2019-01-24
    相关资源
    最近更新 更多