javascript - 如何在一种方法中触发多个视图元素(React Native JS)
问题描述
我们的视图中有两个 WheelPicker。当我们想要改变选择器元素时,其他的选择器也会受到影响。
我该如何解决这个问题。(我不想写两个不同的 Picker Select 方法。我怎么知道在一个方法中调用了哪个选择器。)
选品方式:
constructor(props) {
super(props);
this.state = {
selectedItem : 19,
selectedItem2 : 19,
itemList: numberList
};
}
onPickerSelect (index) {
this.setState({
selectedItem: index,
})
}
onPickerSelect2 (index) {
this.setState({
selectedItem2: index,
})
}
选择器视图:
<Picker style={{width: "100%", height: "100%"}}
selectedValue={this.state.selectedItem}
itemStyle={{width: "100%", height: "100%", color:"#e88554", fontSize:26, }}
onValueChange={(index) => this.onPickerSelect(index)}>
{this.state.itemList.map((value, i) => (
<PickerItem label={value} value={i} key={"money"+value}/>
))}
</Picker>
第二个选择器:
<Picker style={{width: "100%", height: "100%"}}
selectedValue={this.state.selectedItem}
itemStyle={{width: "100%", height: "100%", color:"#e88554", fontSize:26, }}
onValueChange={(index) => this.onPickerSelect2(index)}>
{this.state.itemList.map((value, i) => (
<PickerItem label={value} value={i} key={"money"+value}/>
))}
</Picker>
解决方案
一种解决方案是向 onPickerSelect 添加第二个参数,其中包含 state 属性的名称。
constructor(props) {
super(props);
this.state = {
selectedItem : 19,
selectedItem2 : 19,
itemList: numberList
};
}
onPickerSelect(index, selectedItem) {
this.setState({
[selectedItem]: index,
})
}
<Picker style={{width: "100%", height: "100%"}}
selectedValue={this.state.selectedItem}
itemStyle={{width: "100%", height: "100%", color:"#e88554", fontSize:26, }}
onValueChange={(index) => this.onPickerSelect(index, 'selectedItem2')}>
{this.state.itemList.map((value, i) => (
<PickerItem label={value} value={i} key={"money"+value}/>
))}
</Picker>
另一个可能更好的解决方案是将带有函数的选择器拆分为一个自己的组件,您在当前文件/组件中包含两次。
推荐阅读
- ruby-on-rails - 从 rails-assets.org 采购宝石有什么作用?
- pdf-conversion - 文本对齐:在生成的 evoPDF 上对齐
- sas - SAS Proc GLM 预测输出
- java - 更新到实现 'com.google.android.gms:play-services-ads:15.0.2' 和类路径 'com.google.gms:google-services:3.3.0' 后出现 Gradle 错误
- powershell - 将 SSL 自动化任务添加到管道
- javascript - 如何在 React Admin 包中显示来自服务器端验证的自定义错误消息?
- postgresql - PostgreSQL/JPA - 在 import.sql 文件中导入函数?
- jasper-reports - 将字符串参数传递给子报表数据集
- java - 单击包含 observableArray 的 tableView 内部的 ImageView 后执行事件
- c++ - 为什么在 boost 图形库的访问者中使用 CRTP 模式?