在反应本机中更改选择器时显示不同的文本

displaying different text when changing the picker in react native

我使用 React Native CRNA 创建了我的应用程序,我想显示数组中的文本。我希望文本根据所选的选择器而改变,因此索引与选择器键相同。

这是我的代码片段

export default class App extends React.Component {
  constructor(props){
        super(props);
        this.state ={
            branches: [],
        }
    }
  componentDidMount(){
    fetch('someURL', {
            method: 'GET',
        })
      .then((response) => response.json())
      .then((responseJson) => {
          this.setState({
          cabang: responseJson.data,
          loading: true,
          })
          responseJson.forEach((item)=>{
          this.state.cabang.push({
           branch_id:item.branch_id,
           name: item.name,
           address: item.address,
          })
          })
          branches.map((items)=>{console.log(item.name)})
          console.log(responseJson);
          return responseJson;
      })
        .catch(error=>{
            console.log(error);
        });
    }
  render() 
  {
    const branchesName = this.state.branches.map((item, branch_id)=> {
      return(
        <Text>{item.name}</Text>)
    });
    const branchesPicker = this.state.branches.map((item, branch_id)=> {
      return(
            <Picker.Item
            label={item.name}
            value={item.name}
            key={this._keyExtractor}/>
        )
    });
    return (
      <Text>{branchesName}</Text>
      <Picker selectedValue={this.state.branches.name}
          mode="dropdown"
          style={{ height: 50, justifyContent: 'space-around', flex:4, alignItems: 'stretch', }}
          onValueChange={(item, branch_id)=> this.setState({name: item})}>
      {branchesPicker}
      </Picker>
    );
  }
}

我试过这段代码,但结果显示的是数组中的所有数据,而不是一一显示。我很难找到一种方法来根据所选的选择器一个一个地显示它...有人可以帮我吗??

非常感谢..

在您的渲染方法中,您正在映射数组列表并返回 <Text> 个元素的数组。

const branchesName = this.state.branches.map((item, branch_id)=> { return( <Text>{item.name}</Text>) });

如果你只想显示选中的数组项,你可以改变(在你的渲染方法中)

<Text>{branchesName}</Text>

<Text>{this.state.name}</Text>

这是因为在 Picker 元素中,无论何时更改选定的选取器,都会将其分配给 属性 名称下的组件状态。