我正在尝试使用高阶组件 (HOC) 模式来重用一些连接到状态并使用 Redux Form formValueSelector 方法的代码。
formValueSelector 需要一个引用表单名称的字符串。我想动态地设置它,并能够在我需要项目的值时使用这个 HOC。我使用项目值进行计算。
在下面的代码中,HOC 传递了组件和字符串。我想将其设置为从父级(表单)传入的 Prop formName。
我是 HOC 模式的新手,因此非常感谢任何提示。
高级组织
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { formValueSelector } from 'redux-form';
function FormItemsValueSelectorHOC(FormElement, formName) {
const selector = formValueSelector(formName);
@connect(state => {
console.log(state);
const items = selector(state, 'items');
return {
items
};
}, null)
class Base extends Component {
render() {
return (
<FormElement {...this.props} />
);
}
}
return Base;
}
export default FormItemsValueSelectorHOC;
包装组件
import React, { Component, PropTypes } from 'react';
import { Field } from 'redux-form';
import formItemsValueSelectorHOC from '../Utilities/FormItemsValueSelectorHOC';
const renderField = ({ placeholder, input, type}) => {
return (
<input
{...input}
placeholder={placeholder}
type={type}
/>
);
};
class StatementLineItemDesktop extends Component {
static propTypes = {
items: PropTypes.array.isRequired,
index: PropTypes.number.isRequired,
item: PropTypes.string.isRequired,
fields: PropTypes.object.isRequired,
formName: PropTypes.string.isRequired
};
calculateLineTotal(items, index) {
let unitPrice = '0';
let quantity = '0';
let lineTotal = '0.00';
if (items) {
if (items[index].price) {
unitPrice = items[index].price.amountInCents;
}
quantity = items[index].quantity;
}
if (unitPrice && quantity) {
lineTotal = unitPrice * quantity;
lineTotal = Number(Math.round(lineTotal+'e2')+'e-2').toFixed(2);
}
return <input value={lineTotal} readOnly placeholder="0.00" />;
}
render() {
const { items, index, item, fields, formName} = this.props;
return (
<tr id={`item-row-${index}`} key={index} className="desktop-only">
<td>
<Field
name={`${item}.text`}
type="text"
component={renderField}
placeholder="Description"
/>
</td>
<td>
<Field
name={`${item}.quantity`}
type="text"
component={renderField}
placeholder="0.00"
/>
</td>
<td>
<Field
name={`${item}.price.amountInCents`}
type="text"
component={renderField}
placeholder="0.00"
/>
</td>
<td className="last-col">
<Field
name={`${item}.price.taxInclusive`}
type="hidden"
component="input"
/>
{::this.calculateLineTotal(items, index)}
<a
className="remove-icon"
onClick={() => fields.remove(index)}
>
<span className="icon icon-bridge_close" />
</a>
</td>
</tr>
);
}
}
export default formItemsValueSelectorHOC(StatementLineItemDesktop, 'editQuote');
最佳答案
TLDR:使用ownProps 参数
你应该做什么的草案
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { formValueSelector } from 'redux-form';
function FormItemsValueSelectorHOC(FormElement) {
@connect((state, ownProps) => {
const formName = ownProps.formName;
const selector = formValueSelector(formName);
const items = selector(state, 'items');
return {
items
};
}, null)
class Base extends Component {
render() {
// Now in here you should omit `formName` from the props you are
// passing to your Form Element since it's not used overthere
return (
<FormElement {...this.props} />
);
}
}
return Base;
}
export default FormItemsValueSelectorHOC;
这将是您创建连接组件的方式
formItemsValueSelectorHOC(StatementLineItemDesktop);
这将是你使用它的方式
<ConnectedStatementLineItemDesktop formName={"editQuote"} />
让我再解释一下这是如何工作的
你缺少的是 React-Redux API,你可能应该更多地探索它,因为它已经考虑了很多这样的用例
因此,React-Redux 的connect 函数的第一个参数称为mapStateToProps。
这是它的签名:
mapStateToProps(state, [ownProps]): stateProps
我要强调的是 ownProps 参数。
ownProps 包含传递给连接组件的所有 Prop 。
只是为了澄清,你有这些组件
StatementLineItemDesktop 和 BaseConnectedBase = connect(mapStateToProps)(Base)因此,根据此信息,您的名为 FormItemsValueSelectorHOC 的 HOC 函数返回 ConnectedBase 的变体。
因此,无论您传递给 ConnectedBase 的任何 props 或它从 FormItemsValueSelectorHOC 返回的任何组件,您都可以从 ownProps
顺便说一句,在您的特定情况下,这是您的 mapStateToProps
function mapStateToProps(state, ownProps) {
const formName = ownProps.formName;
const selector = formValueSelector(formName);
const items = selector(state, 'items');
return {
items
};
}
需要注意的是 connect 也是一个 HOC,所以从逻辑上讲,你可以用普通组件做的大部分事情你也可以用连接组件做,我会建议您阅读 connect 源代码,它不长也不难,因此您可能会探索和理解这个答案的更多内容。
希望对您有所帮助。
关于javascript - 调用高阶组件时在 React 类外访问 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39886189/
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
如何在ruby中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
我需要一些关于TDD概念的帮助。假设我有以下代码defexecute(command)casecommandwhen"c"create_new_characterwhen"i"display_inventoryendenddefcreate_new_character#dostufftocreatenewcharacterenddefdisplay_inventory#dostufftodisplayinventoryend现在我不确定要为什么编写单元测试。如果我为execute方法编写单元测试,那不是几乎涵盖了我对create_new_character和display_invent
在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList()Obt
说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时
如何找到调用此方法的位置?defto_xml(options={})binding.pryoptions=options.to_hifoptions&&options.respond_to?(:to_h)serializable_hash(options).to_xml(options)end 最佳答案 键入caller。这将返回当前调用堆栈。文档:Kernel#caller.例子[0]%rspecspec10/16|===================================================62=====
Rails相对较新。我正在尝试调用一个API,它应该向我返回一个唯一的URL。我的应用程序中捆绑了HTTParty。我已经创建了一个UniqueNumberController,并且我已经阅读了几个HTTParty指南,直到我想要什么,但也许我只是有点迷路,真的不知道该怎么做。基本上,我需要做的就是调用API,获取它返回的URL,然后将该URL插入到用户的数据库中。谁能给我指出正确的方向或与我分享一些代码? 最佳答案 假设API为JSON格式并返回如下数据:{"url":"http://example.com/unique-url"
我正在写一篇关于在Ruby中几乎一切都是对象的博客文章,我试图通过以下示例来展示这一点:classCoolBeansattr_accessor:beansdefinitialize@bean=[]enddefcount_beans@beans.countendend所以从类中我们可以看出它有4个方法(当然,除非我错了):它可以在创建新实例时初始化一个默认的空bean数组它可以计算它有多少个bean它可以读取它有多少个bean(通过attr_accessor)它可以向空数组写入(或添加)更多bean(也通过attr_accessor)但是,当我询问类本身它有哪些实例方法时,我没有看到默认
我写了一个非常简单的rake任务来尝试找到这个问题的根源。namespace:foodotaskbar::environmentdoputs'RUNNING'endend当在控制台中执行rakefoo:bar时,输出为:RUNNINGRUNNING当我执行任何rake任务时会发生这种情况。有没有人遇到过这样的事情?编辑上面的rake任务就是写在那个.rake文件中的所有内容。这是当前正在使用的Rakefile。requireFile.expand_path('../config/application',__FILE__)OurApp::Application.load_tasks这里