如何为多个选择器设置选定值

时间:2018-12-24 04:23:29

标签: javascript reactjs react-native

我有一个带有按钮的屏幕,按下该按钮后,将呈现带有选择器的新视图。如果这些选择器都应该彼此独立,如何设置它们的selectedValue?

我尝试使用数组并将索引作为参数传递给视图生成函数,但这似乎不起作用。

import React from "react";
import { View, Picker, Button } from "react-native";

export default class SessionScreen extends React.Component {
  state = {
    externalData: ["Player1", "Player2", "Player3", "Player4"],
    view: [],
    selectedPlayers: []
  };

  async view(index) {
    let players = this.state.externalData.map((s, i) => {
      return <Picker.Item key={i} value={s} label={s} />;
    });
    let newVal = (
      <View
        key={this.state.selectedPlayers[index] + "view" + index}
        style={{ flex: 1, flexDirection: "column", paddingTop: 60 }}
      >
        <View style={{ flexDirection: "row" }}>
          <Picker
            key={this.state.selectedPlayers[index] + "picker" + index}
            selectedValue={this.state.selectedPlayers[index - 1]}
            style={{ height: 50, width: 200 }}
            onValueChange={itemValue =>
              this.setState(prevState => ({
                selectedPlayers: [...prevState.selectedPlayers, itemValue]
              }))
            }
          >
            {players}
          </Picker>
        </View>
      </View>
    );
    await this.setState(prevState => ({
      view: [...prevState.view, newVal]
    }));
  }

  async addPlayer() {
    await this.view(this.state.selectedPlayers.length);
  }

  render() {
    var returnValue = [];
    if (this.state.view.length > 0) returnValue = [...this.state.view];
    returnValue.push(
      <View
        key={returnValue.length + 1}
        style={{ flex: 1, flexDirection: "column", paddingTop: 100 }}
      >
        <Button
          title="Add a player"
          onPress={this.addPlayer.bind(this)}
          accessibilityLabel="Add a new player to the table"
        >
          Add a player
        </Button>
      </View>
    );
    return returnValue;
  }
}

当按下“添加播放器”按钮时,屏幕上会出现一个新的选择器。当我从给定项目中选择其他值时,它仍显示“ Player1”。但是当我再次按下“添加玩家”时,我在第一个选择器中选择的值就会出现在第二个选择器中。

我确信这不是解决此问题的最佳方法,我愿意提出建议。 附言这是我第三天尝试以本机反应或根本不反应。

0 个答案:

没有答案