1

I want to change the background color of flatlist item according to array ans but not able to change background-color of flatlist only 1st item background color is changed

    const ans = [1, 3, 5];
    const [dataSource, setDataSource] = useState([]);

    useEffect(() => {
    let items = Array.apply(null, Array(5)).map((v, i) => {
        return {
            id: i + 1,
        };
    });
    setDataSource(items);
    }, []);
   
    const renderItem = ({ item, index }) => {
        const backgroundColor = item.id == ans[index] ? '#00b300' : "#F5FCFF"; \\ here is main code
       
        return (
            <TouchableWithoutFeedback onPress={() => getItem(item)}>
                <View style={{ ...styles.viewStyle, backgroundColor: backgroundColor, flex: 1 / 5, 
                             height: 40, }} >
                    <Text style={{ ...styles.cardView_Text, color: '#000' }} > {item.id} </Text>
                </View>
            </TouchableWithoutFeedback>
        );
    };

    const getItem = (item) => {
        // alert('Id: ' + item.id);
    };

   <FlatList
    data={dataSource}
    showsHorizontalScrollIndicator={false}
    renderItem={renderItem}
    keyExtractor={(item, index) => index.toString()}
    extraData={selectedId}
    numColumns={5}
    initialNumToRender={2}
    maxToRenderPerBatch={1}
    windowSize={7}
  />        
4

2 回答 2

1

=== is a strict equality comparison operator in JavaScript, which returns false for the values which are not of a similar type. This operator performs type casting for equality. If we compare 2 with "2" using ===, then it will return a false value.

try changing it to == will solve your problem. One more thing please recheck the useState() and useEffect(). Change it to useEffect(), I have added a demo link, Please have a look Link

于 2020-11-24T10:00:27.590 回答
0

what is quesno in your case? and I think you are using useState instead of useEffect.

useState(() => {..}) => useEffect(() => {..})

if you still want to use === and let the code work fine change the function to

const renderItem = ({ item, index }) => {
        const backgroundColor = item.id === ans[index];
       
        return (
            <TouchableWithoutFeedback onPress={() => getItem(item)}>
                <View style={{ ...styles.viewStyle, backgroundColor: backgroundColor  ? '#00b300' : "#F5FCFF" , flex: 1 / 5, 
                             height: 40, }} >
                    <Text style={{ ...styles.cardView_Text, color: '#000' }} > {item.id} </Text>
                </View>
            </TouchableWithoutFeedback>
        );
    };
于 2020-11-24T09:56:52.550 回答