如何在React Native中通过单击按钮更改动态生成的JSX的样式

时间:2020-05-07 16:49:16

标签: javascript reactjs react-native

我正在基于从后端API获得的数组值生成JSX代码。如下图所示,我将根据数组的长度生成这些框。我想要的是,当我单击其中任何一个框时,背景颜色都会改变。

我希望这些框的行为类似于单选按钮,因此一次只有一个框具有不同的背景色。数组名称为“ hasMultipleWeights”。

我只包含了代码的相关部分...


### contents of my_module.py
def testtime_func(path):
  pass

### contents of my_test.py
from my_module import testtime_func

def test():
  testtime_func(1)
  assert True

enter image description here

2 个答案:

答案 0 :(得分:1)

好像您需要创建checkedId状态


 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',
              }}
            >

答案 1 :(得分:1)

要动态更改颜色,必须使用状态。因此,创建一个新状态以检查“选中”按钮,然后在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 },
  },

});