首页 > 解决方案 > 如何在一种方法中触发多个视图元素(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>

标签: javascriptandroidiosreactjsreact-native

解决方案


一种解决方案是向 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>


另一个可能更好的解决方案是将带有函数的选择器拆分为一个自己的组件,您在当前文件/组件中包含两次。


推荐阅读