[英]how to use constructor and update constructor values in JavaScript
我想访问构造函数变量,并在我的代码的某些部分使用它们,我也需要对其进行更新
我正在尝试使用此代码更新react-native Picker值
这就是我使用构造函数的方式:
constructor(props) { super(props); this.Locations = _.uniq(_.map(this.props.Bikes, 'location')); this.selectedLocationValue = this.Locations[0]; }
这是我更新的地方:
<Picker mode='dropdown' selectedValue={this.selectedLocationValue} onValueChange={(itemValue) => { this.selectedLocationValue = itemValue; }} >
我无法将其更改为其他值,这是我面临的问题
<Picker mode='dropdown' selectedValue={this.state.selectedLocationValue} onValueChange={itemValue => this.setState({selectedLocationValue: itemValue}) } >
由于selectedLocationValue
是当前组件的状态,因此应将其置于组件的状态。
在构造函数中添加一个默认值,并将该默认值分配为Locations的第一个值
然后在您的状态下将selectedLocationValue的值分配为默认值,例如:
constructor(props) { super(props); this.Locations = _.uniq(_.map(this.props.Bikes, 'location')); this.defaultValue = this.Locations[0]; } state = { selectedLocationValue: this.defaultValue } <Picker mode='dropdown' selectedValue={this.state.selectedLocationValue} onValueChange={(itemValue) => { this.setState({ selectedLocationValue: itemValue }); }} >
尝试从html标记中删除this
。
<Picker mode='dropdown'
selectedValue={selectedLocationValue}
onValueChange={(itemValue) => { selectedLocationValue = itemValue; }}>
并分享结果。
在您的构造函数中执行此操作
constructor(props) {
super(props);
this.setState({
selectedLocationValue: _.uniq(_.map(this.props.Bikes, 'location'))[0]
});
}
然后在您的选择器组件中执行此操作
<Picker
mode='dropdown'
selectedValue={this.state.selectedLocationValue}
onValueChange={(itemValue) => {
this.setState({ selectedLocationValue: itemValue });
}}
>
设置此使用状态的好处是,每当您更新Picker的值时,它将导致重新渲染,这也将更新您的UI。
您也可以使用this.selectedLocations
完成此操作。 但是React建议任何依赖于UI的东西,因为需要在UI上更改的值应保持在状态中。 这样,每当状态发生变化时,React就会知道并可以相应地更新您的View。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.