我们的视图中有两个WheelPickers。当我们想要更改选择器元素时,其他选择器也会受到影响。
我该如何解决这个问题。 (我不想写两种不同的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 View
<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>
答案 0 :(得分:1)
一个解决方案是向onPickerSelect添加第二个参数,其中包含名称och 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>
另一个,可能更好的解决方案是将具有函数的选择器分解为您在当前文件/组件中包含两次的自有组件。
答案 1 :(得分:0)
您可以在Picker
组件周围创建一个包装器,并将公共值作为props传递。这也将带来更好的代码重用性。
PickerWithID.js (Picker
的包装器组件)
class PickerWithID extends Component {
render() {
const {id , pickerValues, onPickerSelect, itemList } = this.props
return (
<Picker style={{width: "100%", height: "100%"}}
selectedValue={pickerValues[id]}
itemStyle={{width: "100%", height: "100%", color:"#e88554", fontSize:26, }}
onValueChange={(index) => onPickerSelect(index, id)}>
{itemList.map((value, i) => (
<PickerItem label={value} value={i} key={"money"+value}/>
))}
</Picker>
)
}
}
然后,您可以将新的包装器组件用作:
constructor(props) {
super(props);
this.state = {
selectedItems: [19,19], // multiple picker values stored as array
itemList: numberList
};
}
onPickerSelect (index, pickerID) {
const { selectedItems } = this.state;
selectedItems[pickerID] = index;
this.setState({
selectedItem
})
}
First Picker:
<PickerWithID
id={0}
pickerValues={this.state.selectedItems}
itemList={this.state.itemList}
onPickerSelect={this.onPickerSelect}
/>
第二选择器:
<PickerWithID
id={1}
pickerValues={this.state.selectedItems}
itemList={this.state.itemList}
onPickerSelect={this.onPickerSelect}
/>
注意:我们也可以使用循环来渲染多个PickerWithID
组件,因为我们只需更改id
。