[英]Not sure how to render this component with click of a button in react-native
[英]How to click on a button only based on ID that is clicked in React-Native?
我想單擊數據列表之一,並在ID與我們在React Native中單擊的ID匹配時更改綠色。 因此,如果我單擊id 1和id 1中的callCircleButton會更改名稱的圖標
按照我的代碼:
constructor(props) {
super(props);
this.state = {
statusButton: true,
dataList: [
{id: 1, name: 'te1'},
{id: 2, name: 'test2'},
]
}
callCircleButton(){
if(this.state.statusButton == true){
this.setState({statusButton: false})
}else{
this.setState({statusButton: true})
}
}
render() {
return(
{this.state.dataList.map((data, i) => {
return (
<View style={{flex:1, flexDirection: 'row'}}>
<Text>data.name</Text>
<TouchableOpacity onPress={() => this.callCircleButton()}>
{ this.state.statusButton ?
<Icon active size={25} name='panorama-fish-eye' style={{marginRight:10, color: 'green'}}/>
:
<Icon active size={25} name='lens' style={{marginRight:10, color: 'white'}}/>
}
</TouchableOpacity>
</View>
)
})}
)
}
單擊時將活動按鈕的ID設置為狀態,並在循環中檢查狀態值。 例:
constructor(props) {
super(props)
this.state = {
activeButton: null,
dataList: [
{ id: 1, name: 'te1' },
{ id: 2, name: 'test2' }
]
}
}
callCircleButton = (id) => {
this.setState({ activeButton: id })
}
render() {
return (
this.state.dataList.map((data, i) => {
return (
<View style={{ flex: 1, flexDirection: 'row' }}>
<Text>{data.name}</Text>
<TouchableOpacity onPress={() => this.callCircleButton(data.id)}>
{this.state.activeButton === data.id ?
<Icon active size={25} name='panorama-fish-eye' style={{ marginRight: 10, color: 'green' }} />
:
<Icon active size={25} name='lens' style={{ marginRight: 10, color: 'white' }} />
}
</TouchableOpacity>
</View>
)
})
)
}
更改您的json數據結構。
constructor(props) {
super(props);
this.state = {
statusButton: true,
dataList: [
{ id: 1, name: 'te1', statusButton: false },
{ id: 2, name: 'test2', statusButton: false },
]
}
}
callCircleButton({ id }) {
const dataList = this.state.dataList.map((data, i) => {
if (data.id === id) return { ...data, statusButton: !data.statusButton };
return data;
});
this.setState({ dataList })
}
render() {
return (
<View style={{ flex: 1, paddingTop: 50 }}>
{
this.state.dataList.map((data, i) => {
return (
<View style={{ flexDirection: 'row' }}>
<Text>{data.name}</Text>
<TouchableOpacity onPress={() => this.callCircleButton(data)}>
{data.statusButton ?
<Icon active size={25} name='panorama-fish-eye' style={{ marginRight: 10, color: 'green' }} />
:
<Icon active size={25} name='lens' style={{ marginRight: 10, color: 'yello' }} />
}
</TouchableOpacity>
</View>
)
})
}
</View>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.