【发布时间】:2019-10-20 12:32:21
【问题描述】:
我正在探索 React,对生命周期方法和父子通信有些困惑。具体来说,我正在尝试创建一个组件,该组件包装一个选择元素并在选择“其他”选项时添加一个输入框。我已经使用getDerivedStateFromProps() 实现了这个,但根据documentation,这个生命周期方法应该很少使用。因此我的问题是:在这种情况下我应该注意和使用另一种模式吗?
这是我的代码,值和选项作为 props 向下传递,父组件的 handleChange() 方法也是如此。所以当 select 或 input 元素发生变化时,首先更新父组件状态,并通过props.value向下传递一个新值。
export default class SelectOther extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
static getDerivedStateFromProps(props) {
let optionIndex = -1;
for (let i = 0; i < props.options.length; i++) {
if (props.options[i].value === props.value) {
optionIndex = i;
break;
}
}
if (optionIndex > -1) {
return {
selected: props.options[optionIndex].value,
text: "",
showInput: false
};
} else {
return {
selected: "",
text: props.value,
showInput: true
};
}
}
handleChange(e) {
this.props.handleChange({
"target": {
"name": this.props.name,
"value": e.target.value
}
});
}
render() {
return (
<div>
<label>{ this.props.label }</label>
<select name={ this.props.name } value={ this.state.selected } onChange={ this.handleChange }>
{
this.props.options.map(option => <option key={option.value} value={option.value}>{option.label}</option>)
}
<option value="">Other</option>
</select>
{
this.state.showInput &&
<div>
<label>{ this.props.label } (specify other)</label>
<input type="text" className="form-control" value={ this.state.text } onChange={ this.handleChange }></input>
</div>
}
</div>
)
}
}
【问题讨论】:
标签: javascript reactjs