【发布时间】:2021-08-03 04:03:27
【问题描述】:
我有表单组件。
class Form extends Component {
render() {
const fields = [
{
id: 'first-name',
name: 'first_name',
label: 'First Name,
type: text,
defaultValue: 'Nick',
isShowing: true
},
{
id: 'city',
name: 'city',
label: 'City',
type: 'select',
defaultValue: 'mithriya',
options: [
{
value: 'georgina',
label: 'Georgina'
},
{
value: 'mithriya',
label: 'Mithriya'
}
],
isShowing: false
},
];
return (
<div className="pkg-settings">
<form method="post">
<table className="form-table">
<tbody>
{
fields.map( (field) =>
<Field key={field.id} attr={field} />
)
}
</tbody>
</table>
<p className="submit"><input type="submit" name="submit" id="submit" className="button button-primary button-large" value="Save Changes" /></p>
</form>
</div>
)
表单字段分别是不同的组件:
class Field extends Component {
constructor(props) {
super(props);
this.state = {
value: props.attr.defaultValue,
isShowing: props.attr.isShowing
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
this.setState(
{
value: event.target.value
}
);
if ( 'city' === event.target.name && 'georgina' === event.target.value) {
// I'd need to change First Name's isShowing. City's isShowing can be changed by using: this.setState.
}
}
render() {
var element = '';
switch(this.props.attr.type) {
case 'text':
element = <input
type="text"
onChange={this.handleInputChange}
name='first_name'
value={this.state.value}
/>;
break;
case 'select':
element = <select
name='city'
value={this.state.value}
onChange={this.handleInputChange}>
{
this.props.attr.options.map( (option) =>
<option key={option.value} value={option.value}>{option.label}</option>
)
}
</select>
break;
return (
this.state.isShowing
?
<tr valign="top">
<th scope="row">{this.props.attr.label}</th>
<td>
{element}
</td>
</tr>
:
null
);
}
有了这个,我可以更改我当前正在更改的字段的 isShowing,但我想根据当前字段的值更改另一个字段的 isShowing。
this 始终与当前字段有关。还是我做错了?所有字段都应该属于同一个类吗?
感谢您的帮助!
【问题讨论】:
-
这里所有指出状态需要向上移动(到
Form而不是个人Field)的答案都是100% 正确的。此外,显示或不显示字段的逻辑可以是派生状态(派生自Form组件的状态)。如果你对这个想法产生共鸣,我可以分享一个解决方案。