我使用 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 元素中,无论何时更改选定的选择器,都会将其分配给属性名称下的组件状态。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句