Я изо всех сил поискал в Интернете, как создать интерфейс для выбора продуктов, аналогичный тем, которые реализованы в большинстве основных приложений электронной коммерции (amazon, taobao, shopify ...). Цель состоит в том, чтобы выделить или изменить стили выбранного элемента в списке, одновременно удалив стили ранее выбранного элемента. Я пытаюсь использовать react-native для клонирования такой функции. Будем очень признательны за любые ссылки или руководства о том, как это сделать!
import React, { Component } from 'react';
import { View, Text ,StyleSheet, TouchableOpacity, } from 'react-native';
class Selections extends Component {
state = {
highlighted: false,
id: null
}
// The purpose of this function is to set the state to the target index on press
indexStateHandler = (i) =>{
if (this.state.id === null){
this.setState({
id: i
})
}else{
this.setState({
id:i
})
}
console.info("index: "+i)
console.info("state: "+this.state.id)
}
//The purpose of this function is to set styles for the targeted index
highlightStateHandler = (i) =>{
if (this.state.id === i){
if (!this.state.highlighted){
this.setState({
highlighted:true
})
}
else{
this.setState({
highlighted:false
})
}
}
}
highlightHandler = (i) =>{
// console.info(i)
this.indexStateHandler(i)
this.highlightStateHandler(i)
}
render() {
return (
<View style = {styles.selectionWrapper}>
<View style = {styles.label}><Text style = {{color: "black"}}>{this.props.label}</Text></View>
<View style = {styles.listContainer}>
{this.props.options.map((options, i) => (
<TouchableOpacity onPress = {()=>this.highlightHandler(i)} key = {i}>
<View style = {this.state.highlighted&&this.state.id == i?styles.highlighted:styles.options} > <Text style = {styles.text}>{options}</Text> </View>
</TouchableOpacity>
)
)}
</View>
</View>
);
}
}
const styles= StyleSheet.create({
selectionWrapper:{
width: '100%',
height: 100,
borderWidth: 1,
borderColor: 'red',
},
label:{
flex: 1,
}
,
listContainer:{
flex: 3,
flexDirection: "row",
justifyContent: "space-around",
alignItems: 'center',
// backgroundColor: "#7fffd4"
},
options:{
borderRadius: 10,
padding: 5,
borderWidth: 1,
borderColor: "#d0b783",
// backgroundColor: ""
},
text:{
color: 'black',
textAlign: 'center'
},
highlighted:{
borderRadius: 10,
padding: 5,
borderWidth: 1,
// borderColor: "#d0b783",
backgroundColor: "#d0b783"
}
})
export default Selections
Извините, что вы имеете в виду?
визуализировать выбранный стиль для выбранного элемента, не выбран для не выбран;)



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


.....
.....
.....
<TouchableOpacity
style = {[styles.buttonStyle,{
backgroundColor : item.id === this.state.selectedItem.id ? "red" : "blue"
}]}
>
{
...
...
}
</TouchableOpacity>
.....
.....
.....
Взгляните на TouchableOpacity и Осязаемый и попробуйте запустить примеры, чтобы увидеть, как они работают. Также вы можете комбинировать их для изменения визуальных изменений, меняя стили.
import React, { Component } from 'react' import { AppRegistry, StyleSheet, TouchableOpacity, Text, View, } from 'react-native'
export default class App extends React.Component { constructor(props) {
super(props)
this.state = {
itemEn1: true,
itemEn2: false,
itemEn3: false,
} }
onPress1 = () => {
this.setState({
itemEn1: true,
itemEn2: false,
itemEn3: false,
}) }
onPress2 = () => {
this.setState({
itemEn1: false,
itemEn2: true,
itemEn3: false,
}) }
onPress3 = () => {
this.setState({
itemEn1: false,
itemEn2: false,
itemEn3: true,
}) }
render() {
return (
<View style = {styles.container}>
<TouchableOpacity
style = {this.state.itemEn1 ? styles.buttonEnabled : styles.buttonDisabled}
onPress = {this.onPress1}>
<Text> Item 1 </Text>
</TouchableOpacity>
<TouchableOpacity
style = {this.state.itemEn2 ? styles.buttonEnabled : styles.buttonDisabled}
onPress = {this.onPress2}>
<Text> Item 2 </Text>
</TouchableOpacity>
<TouchableOpacity
style = {this.state.itemEn3 ? styles.buttonEnabled : styles.buttonDisabled}
onPress = {this.onPress3}>
<Text> Item 3 </Text>
</TouchableOpacity>
</View>
) } }
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 10
},
buttonDisabled: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
marginTop: 20
},
buttonEnabled: {
alignItems: 'center',
backgroundColor: 'green',
padding: 10,
marginTop: 20
},
countContainer: {
alignItems: 'center',
padding: 10
},
})
это по функции карты:
export default class DataCollector extends React.Component {
constructor(props) {
super(props);
this.SendBack = this.SendBack.bind(this);
}
SendBack(info) {
console.info("Key is :", info);
this.props.callback(info);
}
render() {
let testData = this.props.data.map(function (articleData, index) {
return (
<View key = {index}>
<TouchableOpacity
activeOpacity = {0.6}
key = {index}
onPress = {() => this.callBack([articleData.id, articleData.name])}>
</TouchableOpacity>
</View>
)
}, this);
return (
<View>
{testData}
</View>
);
}
}
Итак, теперь у вас есть доступ к выбранному элементу и вы можете использовать его для включения / отключения и т. д.
Хороший пример здесь, Али, но что, если вы планируете отображать параметры (элементы для выбора) из объекта или массива с помощью функции map (), а не жестко кодировать параметры для вашей среды? Как бы вам теперь удалось прикрепить состояния к этим параметрам, чтобы при нажатии только целевой параметр или параметры оценивались как истинные (в состоянии) и получали выбранный стиль параметра, в то время как остальные оценивались как ложные?
Я хотел поделиться гифкой о том, что я сделал, но файл был слишком большим. Я собираюсь добавить свой код, чтобы вы увидели, как я подошел к проблеме. Дайте мне знать, что вы думаете.
'условный рендеринг'