如何发送隐藏在 React JS 中的输入?

新手上路,请多包涵

我有这个表格,我想发送这些值。我知道我们必须使用 setState() 来存储数据,但它是如何工作的 input type="hidden"

  1. 第一个问题:如何将输入隐藏到 setState ?
  2. 第二个问题:如何序列化像 form.serialize() 这样的数据?
  3. 第三个问题:如何发送这些序列化值? Ajax 和 Axios,谁更好?

这是代码:

 handleSubmit(e) {
    e.preventDefault();

   /**
    $.ajax({
        url: "post.php",
        type: "POST",
        data: DATA,
        success:function(data) {

        }
    });
    **/
 }

            <form onSubmit={this.handleSubmit}>
                        <input type="hidden" name="action" value="login" />
                        <input type="email" name="email_user" placeholder="Email" />
                        <input type="password" name="password_user" placeholder="Mot de passe" />
                        <button type="submit">Login</button>
            </form>

原文由 Steffi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 973
2 个回答

对于您所有的问题,答案都很复杂。

首先,这取决于任务:如果您只是想在表单提交时向服务器发送异步请求,则不需要使用 Component 状态。这是 文档 相关部分的链接。并使用 refs 访问输入数据。

 class FormComponent extends React.Component {

    constructor(props) {
        super(props);
        this.onSubmit = this.onSubmit.bind(this);
    }

    onSubmit(e) {
        e.preventDefault();

        // Send your ajax query via jQuery or Axios (I prefer Axios)
        axios.get('your_url', {
            params: {
              action: this.actionInput.value,
              email: this.emailInput.value,
              password: this.passwordInput.value,
            }
          })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });

    }

    render() {
        return (
            <form onSubmit={this.onSubmit}>
                <input type="hidden" name="action" value="login"
                       ref={(input) => { this.actionInput = input }} />

                <input type="email" name="email_user" placeholder="Email"
                       ref={(input) => { this.emailInput = input }}/>

                <input type="password" name="password_user" placeholder="Mot de passe"
                       ref={(input) => { this.passwordInput = input }}/>

                <button type="submit">Login</button>
            </form>
        );
    }
}

原文由 ShabashP 发布,翻译遵循 CC BY-SA 3.0 许可协议

所有数据都可以存储在 React 的状态中,但是如果您仍然需要在表单上输入,您可以这样做:

 const handleSubmit = e => {
     e.preventDefault();
     const inputs = Object.values(e.target)
        .filter(c => typeof c.tagName === 'string' && c.tagName.toLowerCase() === 'input')
        .reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});

     setFormVals({ ...formVals, ...inputs });
}

请参阅下面的演示:

 const Demo = () => {
    const [formValues] = React.useState({});

    const handleSubmit = e => {
        e.preventDefault();
        const inputs = Object.values(e.target)
            .filter(c => typeof c.tagName === 'string' && c.tagName.toLowerCase() === 'input')
            .reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});

        console.log(inputs);
    }

    return (
        <form onSubmit={handleSubmit}>
            <input name="name" placeholder="Name" value={formValues.name} />
            <input name="email" placeholder="Email" value={formValues.email} />
            <input name="hiddenInput" value="hiddenValue" type="hidden" />
            <button type="submit">Submit</button>
        </form>
    );
}

ReactDOM.render(<Demo />, document.getElementById('demo'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>

<div id="demo"></div>

如果你知道你需要什么输入,你可以这样做:

 const Demo = () => {
    const formRef = React.useRef(null);
    const [formValues, setFormValues] = React.useState({});

    const handleChange = e => {
      setFormValues({
        ...formValues,
        [e.target.name]: e.target.value,
      });
    }

    const handleSubmit = e => {
      e.preventDefault();
      setFormValues({ ...formValues, hiddenInput: formRef.current.hiddenInput.value });
    }

    return (
        <form onSubmit={handleSubmit} ref={formRef}>
            <input name="name" placeholder="Name" value={formValues.name} onChange={handleChange} />
            <input name="email" placeholder="Email" value={formValues.email} onChange={handleChange} />
            <input name="hiddenInput" value="hiddenValue" type="hidden" />
            <button type="submit">Submit</button>
            <pre>{JSON.stringify(formValues, null, 2)}</pre>
        </form>
    );
}

ReactDOM.render(<Demo />, document.getElementById('demo'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>

<div id="demo"></div>

原文由 Abraham 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进