在 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>
);
}
}

我尝试了这段代码,但结果是显示数组中的所有数据,而不是一个接一个。我非常困在找不到一种方法根据选定的选择器一一显示它......谁能帮我??

非常感谢。。

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

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

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

<Text>{branchesName}</Text>

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

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

最新更新