簡體   English   中英

如何通過在 React Native 中單擊按鈕來更改動態生成的 JSX 的樣式

[英]How change the styling of dynamically generated JSX via a button click in React Native

我正在根據從后端 API 獲得的數組值生成 JSX 代碼。 如下圖所示,我正在根據數組的長度生成這些框。 我想要的是當我單擊任何這些框時,背景顏色會發生變化。

我希望這些框表現得像一個單選按鈕,因此一次只有一個框具有不同的背景顏色。 數組名稱是“hasMultipleWeights”。

我只包含了代碼的相關部分......

const ProductDetailsScreen = (props) => {

  const productId = props.navigation.getParam("productId");

  const selectedProduct = useSelector((state) =>
    state.products.products.find((prod) => prod.id === productId)
  );


  const productsMultipleWeights = useSelector(
    (state) => state.products.productsMultipleWeights
  );

  var hasMultipleWeights = productsMultipleWeights.find(
    (prod) => Object.keys(prod)[0] == selectedProduct.id
  );

  if (hasMultipleWeights) {
    hasMultipleWeights = hasMultipleWeights[Object.keys(hasMultipleWeights)[0]];

  }


return (
    <ScrollView style={{}}>
      <View style={styles.screen}>

        {hasMultipleWeights && (
          <View style={{ alignItems: "center" }}>
            <ScrollView
              horizontal
              contentContainerStyle={{ padding: 2 }}
              showsHorizontalScrollIndicator={false}
            >
              {hasMultipleWeights.map((item) => (
                <TouchableOpacity
                  key={item.id}
                  onPress={() => {}}
                  style={{
                    ...styles.productOptions,
                    backgroundColor: 'white',
                  }}
                >
                  <Text style={styles.productWeightVolumUnit}>
                    <Text style={styles.productWeightVolumeValue}>
                      {NS(item.weight, "Arabic")}
                    </Text>
                    {"  "}
                    {selectedProduct.weightVolumeUnit}
                  </Text>
                  <MaterialCommunityIcons
                    name={
                      selectedProduct.weightVolumeUnit === "كغ"
                        ? "weight-kilogram"
                        : selectedProduct.weightVolumeUnit === "مل"
                        ? "water"
                        : "weight-gram"
                    }
                    size={26}
                    color="grey"
                    style={styles.weightIcon}
                  />
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>
        )}
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({

productOptions: {
    shadowColor: "black",
    shadowOpacity: 0.26,
    elevation: 5,
    borderRadius: 10,
    backgroundColor: "white",
    width: 85,
    height: 65,
    marginHorizontal: 6,
    alignItems: "center",
    justifyContent: "center",
    shadowRadius: 2,
    shadowOffset: { width: 0, height: 1 },
  },

});

在此處輸入圖像描述

好像你需要創建checkedId state


 const [ checkedId, setCheckedId ] = useState('')

 useEffect(() =>
    // set first box to red at first render
    hasMultipleWeights && setCheckedId(hasMultipleWeights[0].id) ,[ hasMultipleWeights ])


 ...

 <TouchableOpacity
              key={item.id}
              onPress={() =>setCheckedId(item.id)}
              style={{
                ...styles.productOptions,
                backgroundColor: item.id == checkedId ? 'red' : 'white',
              }}
            >

要動態更改顏色,您必須使用 state。 因此,創建一個新的 state 來檢查“選中”的按鈕,在 onPress 方法中更改它,然后進行驗證。

const ProductDetailsScreen = (props) => {
  const [checkedButton, setCheckedButton] = React.useState('')

  const productId = props.navigation.getParam("productId");

  const selectedProduct = useSelector((state) =>
    state.products.products.find((prod) => prod.id === productId)
  );


  const productsMultipleWeights = useSelector(
    (state) => state.products.productsMultipleWeights
  );

  var hasMultipleWeights = productsMultipleWeights.find(
    (prod) => Object.keys(prod)[0] == selectedProduct.id
  );

  if (hasMultipleWeights) {
    hasMultipleWeights = hasMultipleWeights[Object.keys(hasMultipleWeights)[0]];

  }


return (
    <ScrollView style={{}}>
      <View style={styles.screen}>

        {hasMultipleWeights && (
          <View style={{ alignItems: "center" }}>
            <ScrollView
              horizontal
              contentContainerStyle={{ padding: 2 }}
              showsHorizontalScrollIndicator={false}
            >
              {hasMultipleWeights.map((item) => (
                <TouchableOpacity
                  key={item.id}
                  onPress={() => setCheckedButton(item.id)}
                  style={{
                    ...styles.productOptions,
                    backgroundColor: checkedButton === item.id ? "grey" : "white",
                  }}
                >
                  <Text style={styles.productWeightVolumUnit}>
                    <Text style={styles.productWeightVolumeValue}>
                      {NS(item.weight, "Arabic")}
                    </Text>
                    {"  "}
                    {selectedProduct.weightVolumeUnit}
                  </Text>
                  <MaterialCommunityIcons
                    name={
                      selectedProduct.weightVolumeUnit === "كغ"
                        ? "weight-kilogram"
                        : selectedProduct.weightVolumeUnit === "مل"
                        ? "water"
                        : "weight-gram"
                    }
                    size={26}
                    color="grey"
                    style={styles.weightIcon}
                  />
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>
        )}
      </View>
    </ScrollView>
  );
};

const styles = StyleSheet.create({

productOptions: {
    shadowColor: "black",
    shadowOpacity: 0.26,
    elevation: 5,
    borderRadius: 10,
    backgroundColor: "white",
    width: 85,
    height: 65,
    marginHorizontal: 6,
    alignItems: "center",
    justifyContent: "center",
    shadowRadius: 2,
    shadowOffset: { width: 0, height: 1 },
  },

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM