我需要根据用户在表单第一步提示的值生成一定数量的字段。
由于我正在使用“向导”类<Condition />
组件进行多步骤表单不起作用。
基本上我需要访问值(从函数组件内的类中提取它们),以便告诉 React 它需要生成的“页面”数量。
像这样的东西:
export default () => {(
<Wizard
initialValues={{ }}
onSubmit={onSubmit}
>
<Wizard.Page >
<FirstStep />
</Wizard.Page>
{values.items.map((item, index) => (
<Wizard.Page key="index">
<SecondStep stepName="item.name" key="index" />
</Wizard.Page>
) )}
</Wizard>
)}
为了根据用户创建的商品数量生成N页,每个商品一页。
这种方法不起作用,因为它告诉我没有定义值。
这是我的向导反应组件:
import React from 'react'
import PropTypes from 'prop-types'
import { Form } from 'react-final-form'
import arrayMutators from 'final-form-arrays'
export default class Wizard extends React.Component {
static propTypes = {
onSubmit: PropTypes.func.isRequired
}
static Page = ({ children }) => children
constructor(props) {
super(props)
this.state = {
page: 0,
values: props.initialValues || {}
}
}
next = values =>
this.setState(state => ({
page: Math.min(state.page + 1, this.props.children.length - 1),
values
}))
previous = () =>
this.setState(state => ({
page: Math.max(state.page - 1, 0)
}))
validate = values => {
const activePage = React.Children.toArray(this.props.children)[
this.state.page
]
return activePage.props.validate ? activePage.props.validate(values) : {}
}
handleSubmit = values => {
const { children, onSubmit } = this.props
const { page } = this.state
const isLastPage = page === React.Children.count(children) - 1
if (isLastPage) {
return onSubmit(values)
} else {
this.next(values)
}
}
render() {
const { children } = this.props
const { page, values } = this.state
const activePage = React.Children.toArray(children)[page]
const isLastPage = page === React.Children.count(children) - 1
return (
<Form
initialValues={values}
validate={this.validate}
onSubmit={this.handleSubmit}
mutators={{...arrayMutators }}
>
{({ handleSubmit, submitting, values }) => (
<form onSubmit={handleSubmit}>
{activePage}
<div className="buttons centered">
{page > 0 && <button type="button" onClick={this.previous} >« Previous </button>}
{!isLastPage && <button type="submit">Next »</button>}
{isLastPage && <button type="submit" disabled={submitting}>Submit</button>}
</div>
<pre>{JSON.stringify(values, 0, 2)}</pre>
</form>
)}
</Form>
)
}
}
这是 FirstStep 组件(用户插入它的第一个值,它生成项目数组。我需要做的就是拉出状态的值,以便根据第一个数组的长度生成多个页面):
export default () => (
<FieldArray name="items">
{({ fields }) => (
<div className="centered-items">
{fields.map((name, index) => (
<div key={name} className="item-row">
<label htmlFor={`item-name-${index}`}>item: </label>
<Field
id={`item-name-${index}`}
name={`${name}.item`}
component="input"
type="text"
placeholder="Place Item Name"
/>
<button type="button" onClick={() => fields.remove(index)}>
Remove
</button>
</div>
))}
<button
className="centered"
type="button"
onClick={() => fields.push({ tipologia: '', numero_camere: '1' })}
>
Add Item
</button>
</div>
)}
</FieldArray>
)