ReactJS使用默认值提交表单

问题描述 投票:1回答:2

组件具有FormControl(react-bootstrap),可以定义defaultValue。

这个想法是:当定义该默认值时,表单提交。

我已经尝试定义componentDidMount()函数,但它无限循环(渲染 - 提交 - 渲染...)

编辑:我不允许共享生产代码(公司政策)。相反,我制作了一个片段来试图解释这种情况:

export default class MyForm extends React.Component {
    componentDidMount() {
        // This was my first approach.
        // Which did not work since after submitting
        // the component re-renders, submits and so on...
        if (this.props.defaultValue) {
            document.getElementById('formName').submit();
        }
    }

    handleFormSubmit(event) {
        event.preventDefault();
        // doSomethingWithFormData(event);
    }

    render() {
        <Form inline onSubmit={(ev) => this.handleFormSubmit(ev)} id='formName'>
            <FormGroup controlId="ValueFormGroup">
                <FormControl
                    type="text"
                    id="formName"
                    name="fieldName"
                    required={true}
                    defaultValue={this.state.value}
                />
                &nbsp;
                <Button 
                    type="submit"
                    bsStyle="primary"
                </Button>
            </FormGroup>
        </Form>
    }
}

可以通过GET参数(defaultValue)接收FormControl http://url.com/something?value=aValue的值。 如果收到这样的值,表格的输入将被填写并提交表格。然后,将向REST服务询问结果,最后,当它们到达时,填写表单下方的表格。所有这些都是由handleFormSubmit()完成的。

表单提交后,页面将无限期地重新加载。

javascript reactjs react-bootstrap
2个回答
0
投票

我找到了解决方案。我正在写下面的细节,以防有人发现它们有用:解决问题:

componentDidMount() {
    if (this.props.defaultValue) {
        const event = new Event('submit', {cancelable: true});
        document.getElementById('formName').dispatchEvent(event);
    }
}

{cancelable: true}是最重要的事情,因为event.preventDefault();工作(防止页面重新加载),事件必须是cancellable

我不是反应专家,所以我愿意接受建议:)


0
投票

您可以直接从submit()调用doSomethingWithFormData,而不是在DOM元素上调用componentDidMount

componentDidMount() {
  if (this.props.defaultValue) {
    doSomethingWithFormData(this.props.defaultValue)
  }
}

这不会触发表单提交或页面重新加载。

© www.soinside.com 2019 - 2024. All rights reserved.