首页 > 解决方案 > 在无状态反应组件中让表单提交数据的正确方法是什么?

问题描述

我有一个无状态的反应组件,它有点弹出。它从用户那里获取一些数据,并将其传递回它的父级,在那里它执行工作。

这个组件拥有一个 handleSubmit() 函数的最佳方式是什么,它接受用户输入并将其发送回父级?

import React, { Component } from "react";
import "../../../node_modules/bulma/css/bulma.css";

const Transfer = (props, token, web3) => {
  return (
    <div className="modal is-active">
      <div className="modal-background" onClick={props.onClick} />
      <div className="modal-card">
        <section className="modal-card-body">
          <div className="content">
            <h1 className="title"> Transfer Tokens </h1>
            <p className="has-text-danger">
              Requires that you are the owner of the token you are transferring
            </p>
            <p className="subtitle">How it works</p>
            <p className="">
              Enter the ID of the token you want to transfer, the address to
              whom its going to, and thats it!
            </p>
            //problem area
            <form onSubmit={props.onClickSubmit}>
              <label htmlFor="text">Address to recieve token</label>
              <input
                name="Address"
                className="input is-info "
                required="true"
              />
              <label htmlFor="number">Token ID</label>
              <input
                className="input is-info"
                name="Token ID"
                type="number"
                required="true"
              />
              <a className="button is-pulled-right">Submit</a>
            </form>
          </div>
        </section>
        <footer className="modal-card-foot is-clearfix">
          <a className="button" onClick={props.onClick}>
            Cancel
          </a>
        </footer>
      </div>
    </div>
  );
};

export default Transfer;

我在父组件中作为道具 onClickSubmit 传入,其中包含我正在尝试做的事情的逻辑。

无状态反应组件非常新

标签: javascriptreactjsreact-router

解决方案


使用无状态组件很难实现您想要的,因为您不能使用无状态组件refsstate在无状态组件中使用。props您可以将无状态组件视为一个纯函数,它根据您给它的内容返回一段 UI 。

您可以改为使用有状态组件,例如将输入值存储在其中,并在用户提交表单时使用它state调用onClickSubmitprop 函数。state


推荐阅读