如何在JavaScript中使用构造函数和更新构造函数值

时间:2017-11-06 06:40:38

标签: javascript react-native

我想访问构造函数变量并在代码的某些部分使用它们我需要更新它

我正在尝试使用此代码更新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; }}
>
&#13;
&#13;
&#13;

我无法将其更改为其他值,这是我面临的问题

4 个答案:

答案 0 :(得分:1)

<Picker
  mode='dropdown'
  selectedValue={this.state.selectedLocationValue}
  onValueChange={itemValue => this.setState({selectedLocationValue: itemValue}) }
>

因为selectedLocationValue是当前组件的状态,所以应该将其置于组件的状态。

答案 1 :(得分:1)

在构造函数中添加默认值,并将该默认值指定为“位置”的第一个值

然后在您的状态中将selectedLocationValue的值指定为默认值 喜欢:

&#13;
&#13;
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 }); }}
  >
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试从html标记中删除this

<Picker mode='dropdown'
 selectedValue={selectedLocationValue}
 onValueChange={(itemValue) => { selectedLocationValue = itemValue; }}>

并分享结果。

答案 3 :(得分:0)

在你的构造函数中执行此操作

constructor(props) {
   super(props);
   this.setState({
       selectedLocationValue: _.uniq(_.map(this.props.Bikes, 'location'))[0]
   });
}

然后在你的Picker Component中执行此操作

<Picker
  mode='dropdown'
  selectedValue={this.state.selectedLocationValue}
  onValueChange={(itemValue) => { 
     this.setState({ selectedLocationValue: itemValue }); 
  }}
>

设置此状态的好处是,每次Picker的值更新时,它都会导致重新渲染,这也会更新您的UI。

您也可以使用this.selectedLocations完成此操作。但是React推荐任何与UI相关的内容,因为需要在UI上更改的值应该保持在状态。因此,每当状态发生变化时,React都会知道,并且可以相应地更新您的View。

相关问题