简体   繁体   中英

Change and toggle background color of an button(from 2/3 button list) when clicked - React Native

I am trying to change a button background color when clicked and toggle between list of buttons within the same button list. I ahve been trying this since yesterday and stuck at point where i am not able to proceed further.

More details - I have a page with questions and multiple option for the question and use should only select either of the answer YES/No/NA and that button background should be changed to different color, it works for a single question but for multiple questions i am not understanding which unique value to use to toggle the button color with in the same question.

I have created a snack for it here is an URL - https://snack.expo.io/@jerrypatels/bossy-bagel for some reason the snack is not working as expected on web but works well with mobile view, so request you to try the mobile version.

Now if i click first question YES it changes the color of all questions to YES.

Image how it is working在此处输入图像描述

How i need it to look like在此处输入图像描述

The state checked is on your AlongsideScreen component, not on each individual set of buttons as you probably intended. You probably want to split up the list of questions, list of buttons and everything like that into their own separate components to make managing the state easier, and you might want to consider using class components. Also, when you run into a problem, try simplifying the problem to allow you to understand it easier. You have a lot of extra code in your example that isn't related to the problem that I'm just going to replace with ... for now.

By breaking it up, the error becomes obvious:

const AlongsideScreen = ({ navigation }) => {
    const [along, setAlong] = useState();
    const [checked, setChecked] = useState();

    return (
        // ... other view code here
        <View style={styles.containerText}>
            // We pass in our questions as a prop to QuestionsList.
            <QuestionsList questions={Questions}> </QuestionsList>
        </View>
    );
};

const QuestionsList = (props) => {
    return (
        <FlatList
            data={props.questions}
            keyExtractor={(item, index) => '' + index}
            renderItem={({ item }) => (
                <ButtonSelect item={item}></ButtonSelect>
            )}
        />
    )
}

const ButtonSelect = ({ item }) => {
    return (
        <FlatList
            data={item.data}
            keyExtractor={(item, index) => '2' + index}
            renderItem={({ item, index }) => (
                <View style={{ padding: 10 }}>
                    <Text style={[styles.text, { padding: 10 }]}>
                        {item.Q}
                    </Text>
                    <View style={styles.btnP}>
                        {item.options.map((list, ind) => {
                            return (
                              <SelectableButton item={item} list={list}></SelectableButton>
                            );
                        })}
                    </View>
                </View>
            )}
        />
    )
}

const SelectableButton = ({ item, list }) => {
    return (
        <TouchableOpacity
            style={[
                styles.btn2,
                {
                    width: width / item.length - item.width,
                    backgroundColor:
                        checked === list.id // ERROR! checked is undefined
                        ? "red"
                        : '#F4F6FC',
                },
            ]}
            onPress={() => {
                setChecked(list.id); // ERROR! setChecked is undefined!
            }}>
            <Text
                style={[
                    Style.normalText,
                    { textAlign: 'center' },
                ]}>
                {list.value}
            </Text>
        </TouchableOpacity>
    )
}

This is just your code, but it's been rearranged and the parts irrelevant to the issue have been deleted.

To fix the problem that you see above, you should add a prop for a listener for presses to SelectableButton and a prop for whether the button is checked. On the ButtonSelect, you should have a prop for a listener for when the currently selected button changes. Pass in whether the button is checked and a listener to each SelectableButton, and when that listener is called, call the listener prop. You may need to keep repeating this chain up, as there should only be a single source of truth. This is the "React Way".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM