Троичная кнопка onPress изменить цвет React Native

#javascript #reactjs #react-native

#javascript #reactjs #react-native

Вопрос:

Я использую троичное условие для изменения цвета моей кнопки react native при нажатии на нее:

  backgroundColor: { present? "pink": "blue" }
  

Однако, когда я это делаю, я получаю следующую ошибку:

 SyntaxError: /home/chloe/Desktop/application/my-app/screens/Checkin/Items.js: Unexpected token, expected "," (88:156)

  86 |                                 <IconButton icon={user.favCheckinItems.includes(item._id) ? "star" : "star-outline"} color="rgb(194, 154, 39)" size={50} onPress={() => addToFavorites(item._id)} style={{ position: "absolute", marginLeft: Dimensions.get("window").width - 80 }} />
  87 |                                 <View style={{ flex: 1, flexDirection: "row", position: "absolute", bottom: 5 }}>
> 88 |                                     <Button style={{ flex: 1, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1, backgroundColor: { present? "pink": "blue" } }} onPress={() => update("present")}><Text style={{ color: "black" }}>Present</Text></Button>
     |                                                                                                                                                             ^
  89 |                                     <Button style={{ flex: 1, backgroundColor: damanged, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1 }} onPress={() => update("damaged")}><Text style={{ color: "black" }}>Damaged</Text></Button>
  90 |                                     <Button style={{ flex: 1, backgroundColor: missing, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1 }} onPress={() => update("missing")}><Text style={{ color: "black" }}>Missing</Text></Button>
  91 |                                 </View>

TransformError SyntaxError: /home/chloe/Desktop/application/my-app/screens/Checkin/Items.js: Unexpected token, expected "," (88:156)

  86 |                                 <IconButton icon={user.favCheckinItems.includes(item._id) ? "star" : "star-outline"} color="rgb(194, 154, 39)" size={50} onPress={() => addToFavorites(item._id)} style={{ position: "absolute", marginLeft: Dimensions.get("window").width - 80 }} />
  87 |                                 <View style={{ flex: 1, flexDirection: "row", position: "absolute", bottom: 5 }}>
> 88 |                                     <Button style={{ flex: 1, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1, backgroundColor: { present? "pink": "blue" } }} onPress={() => update("present")}><Text style={{ color: "black" }}>Present</Text></Button>
     |                                                                                                                                                             ^
  89 |                                     <Button style={{ flex: 1, backgroundColor: damanged, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1 }} onPress={() => update("damaged")}><Text style={{ color: "black" }}>Damaged</Text></Button>
  90 |                                     <Button style={{ flex: 1, backgroundColor: missing, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1 }} onPress={() => update("missing")}><Text style={{ color: "black" }}>Missing</Text></Button>
  91 |                                 </View>
- node_modules/react-native/Libraries/Utilities/HMRClient.js:326:31 in showCompileError
- node_modules/react-native/Libraries/Utilities/HMRClient.js:238:26 in client.on$argument_1
- node_modules/eventemitter3/index.js:181:21 in emit
- node_modules/metro/src/lib/bundle-modules/HMRClient.js:142:10 in _ws.onmessage
- node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
- node_modules/react-native/Libraries/WebSocket/WebSocket.js:232:8 in _eventEmitter.addListener$argument_1
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:425:19 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:112:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:373:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
  

Я не понимаю, в чем проблема. Это полная часть кода:

 <View>
                                <Image source={{ uri: item.image }} style={{ width: Dimensions.get("window").width, height: 200, marginBottom: 10 }} />
                                <Text style={{ position: "absolute", fontSize: 50, marginLeft: 20, color: 'white' }}>{item.name}</Text>
                                <IconButton icon={user.favCheckinItems.includes(item._id) ? "star" : "star-outline"} color="rgb(194, 154, 39)" size={50} onPress={() => addToFavorites(item._id)} style={{ position: "absolute", marginLeft: Dimensions.get("window").width - 80 }} />
                                <View style={{ flex: 1, flexDirection: "row", position: "absolute", bottom: 5 }}>
                                    <Button style={{ flex: 1, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1, backgroundColor: { present? "pink": "blue" } }} onPress={() => update("present")}><Text style={{ color: "black" }}>Present</Text></Button>
                                    <Button style={{ flex: 1, backgroundColor: damanged, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1 }} onPress={() => update("damaged")}><Text style={{ color: "black" }}>Damaged</Text></Button>
                                    <Button style={{ flex: 1, backgroundColor: missing, margin: 10, borderRadius: 10, borderColor: "black", borderWidth: 1 }} onPress={() => update("missing")}><Text style={{ color: "black" }}>Missing</Text></Button>
                                </View>
                            </View>
  

И это функция обновления :

    const update = (state) => {
        if (state == "present") {
            setPresent(!present)
        }
        console.log(present)
    }
  

И это инициализация :

 const [present, setPresent] = useState(false)
  

Комментарии:

1. Если я правильно понимаю, style принимает объект в качестве значения. Таким образом, вы добавляете объект в качестве backgroundColor, но его недопустимый объект.

2. Итак, как я могу изменить цвет фона кнопки при нажатии?

3. Попробуйте удалить фигурные скобки. Вместо backgroundColor: { present? "pink": "blue" } этого выполните backgroundColor: present? "pink": "blue"

Ответ №1:

Здесь вам не нужны фигурные скобки:

 // backgroundColor: { present? "pink": "blue" } <- Type Error

// Right syntax
backgroundColor: present? "pink": "blue"