상태에 연결하는 일부 코드를 재사용하기 위해 Higher Order Component (HOC) 패턴을 사용하려고하고 Redux Form formValueSelector 메소드를 사용하고 있습니다.Higher Order 구성 요소를 호출 할 때 React에서 클래스 외부의 소품에 액세스하십시오.
formValueSelector는 양식의 이름을 참조해야합니다. 이 항목을 동적으로 설정하고 항목 값이 필요할 때마다이 HOC를 사용할 수 있어야합니다. 계산에 항목 값을 사용합니다.
아래 코드에서 HOC는 구성 요소와 문자열을 전달합니다. 부모 (양식)에서 전달 된 propFormName으로 설정하고 싶습니다.
나는 HOC 패턴을 처음 사용하기 때문에 어떤 조언을 가장 높이 평가할 수 있습니다.
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');
나에게 명확한 지 모르겠지만 반응 구성 요소'StatementLineItemsDesktop' 클래스를 내보내고 호출 할 수 있도록 부모 구성 요소가 선언 된 파일에서이 React 구성 요소를'formItemsValueSelectorHOC' 함수와 함께 가져 오는 것으로 생각 해보았습니까 두 번째 인수로'this.props.formName'을 사용하여 부모의'render()'메소드에있는이 HOC? – dzv3