【发布时间】:2018-12-22 08:16:49
【问题描述】:
我有一个无状态的反应组件,它有点弹出。它从用户那里获取一些数据,并将其传递回它的父级,在那里它执行工作。
让这个组件拥有一个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 传入,其中包含我要执行的操作的逻辑。
对无状态反应组件非常陌生
【问题讨论】:
-
您很可能希望使用有状态组件并将输入值存储在 state 中,并将其用作
onClickSubmitprop 函数的参数。 -
这是我的解决方案,但这是一个非常小的组件,它只是获取几条数据而已。无状态似乎是完美的组件?如果这个组件不能是无状态的,那我觉得我做的无状态组件错了?
-
您不能在无状态组件中使用 state 或 refs,因此如果不将其转换为有状态组件,您真的没有工具可以完成您想要的事情。如果您的组件仅依赖于给它的 props,那么无状态组件非常适合。但是,如果它们不适合您的用例,那么尝试强制使用无状态组件是没有意义的。
-
好的。感谢您的反馈。您可以分享的任何资源都涉及到 React 的更深层次和更新方面,而不是基础知识?我掌握了基础知识,但是当尝试深入研究新的/更深入的事物时,很难学习
-
我个人对文档的Main concepts 和Advanced Guides 部分中列出的技术了解不多。其余的我觉得只是对某些库和 JavaScript 的一般经验。
标签: javascript reactjs react-router