我有一个复杂的表单,某些字段的可见性取决于其他字段的值。 如何根据以redux-form完成的其他字段的值设置字段的可见性?
const renderField = ({ input, label, type, display='flex', meta: { touched, error } }) => (
<div style={ { display: display }}>
<label>{label}</label>
<div>
<input {...input} type={type} placeholder={label}/>
{touched && error && <span>{error}</span>}
</div>
</div>
)
const renderMembers = ({ fields, meta: { touched, error } }) => (
<ul>
<li>
<button type="button" onClick={() => fields.push({})}>Add Member</button>
{touched && error && <span>{error}</span>}
</li>
{fields.map((member, index) =>
<li key={index}>
<button
type="button"
title="Remove Member"
onClick={() => fields.remove(index)}/>
<h4>Member #{index + 1}</h4>
<Field
name={`${member}.firstName`}
type="text"
component={renderField}
label="First Name"/>
<Field
name={`${member}.lastName`}
type="text"
component={renderField}
label="Last Name"/>
<Fields names={[ `${member}.firstName`, `${member}.lastName` ]} component={renderFields}/>
<FieldArray name={`${member}.hobbies`} component={renderHobbies}/>
</li>
)}
</ul>
)
答案 0 :(得分:2)
假设您有一个包含2个字段的表单:
const fields = [
'foo',
'bar'
]
reduxForm(
{
form: 'AwesomeForm',
fields
}
)(AwesomeForm)
要根据<AwesomeForm/>
组件中的其他字段值控制字段可见性,您可以使用内联样式设置相应的display
值。只需进行验证,检查其他值是否满足所需条件。喜欢:
export const AwesomeForm = (props) => {
return (
<form onSubmit={props.handleSubmit}>
<TextField
{...props.fields.foo}
/>
<TextField
{...props.fields.bar}
style={{
display: props.fields.name.foo === 'some value' ? 'none' : 'block',
}}
/>
<button
type='submit'
/>
</form>
)
}