javascript - 使用 setNativeProps 重置/更改选择器(下拉)selectedValue

标签 javascript react-native

我有一个带有 TextInput、Picker 和 TouchableHiglight 的表单。

用户将在 TextInput 中输入内容,从 Picker 中选择一个项目并使用 TouchableHighlight 提交。

我可以使用 ref 来重置 TextInput,但我不知道如何将 Picker 值更改/重置为默认值。

Possible Unhandled Promise Rejection
TypeError: this.value2ref.setNativeProps is not a function

React-Native

constructor(props) {
  super(props);
  this.state = {
    value1: '',
    value1ref: '',
    value2: '',
    value2ref: ''
  }
}

<TextInput
  onChangeText={(text) => this.setState({value1:text})}
  ref={input => {this.value1ref=input}}
/>

<View>
  <Picker
    selectedValue={this.state.value1}
    onValueChange={(itemValue, itemIndex) => this.setState({value2: itemValue})}
    ref={input => {this.value2ref=input}}>
    <Picker.Item label="Pick an item" value="" />
    <Picker.Item label="Item 1" value="Item1" />
    <Picker.Item label="Item 2" value="Item2" />
    <Picker.Item label="Item 3" value="Item3" />
  </Picker>
</View>

<View>
  <TouchableOpacity onPress={this.onSubmit.bind(this)}>
    <View>
      <Text>SUBMIT</Text>
    </View>
  </TouchableOpacity>
</View>

我也尝试过这种类型的引用,但无济于事。

ref={component => this._exampleref=component}>

JavaScript

onSubmit() {
  this.value1ref.setNativeProps({ //This one works
    text: "",
  });
  this.value2ref.setNativeProps({ // This one does NOT work
    selectedValue: "",
  });
}

我知道我可以使用 this.value1ref.clear() 但我这样做是为了证明一个观点,而且,没有 clear() 用于选择器。

最佳答案

我认为您不应该为此使用 refs。

您正在使用 onChangeTextonValueChange 中的回调正确更新状态,但您没有从状态呈现,因为您需要添加 prop 到 TextInput 您已经为选择器使用了 selectedValue 因此行为不同(虽然 prop 中使用的值可能是错误的)。

<TextInput
  onChangeText={(text) => this.setState({value1:text})}
  value={this.state.value1}
/>

<Picker
  selectedValue={this.state.value2}
  onValueChange={(itemValue) => this.setState({value2: itemValue})}
  >
  {/* ... */}
</Picker>

有了这个集合,您只需要在您的 onSubmit 中使用它即可。

onSubmit() {
  this.setState({value1: '', value2: ''});
}

关于javascript - 使用 setNativeProps 重置/更改选择器(下拉)selectedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47253936/

相关文章:

ios - 为 react-native 添加了 IOS QuickLook 框架

android - React Native - 无法在 Android 的前台访问 Firebase 推送通知

javascript - moment.js 时间计算错误

javascript - Jquery Accordion 从外部链接激活

javascript - Prop 类型失败 : Invalid prop 'value' of type 'object' supplied to 'TextInput' React Native

react-native - AsyncStorage 返回 [Object] [Object]

android - React Native 的项目结构包括原生 iOS,Android?

对象的 Javascript 原型(prototype)继承和链接构造

javascript - 使用 AngularJS 进行文件哈希处理

javascript - MediaElement.js可以用于播放IE6-8,Firefox和Opera的音频吗?