简体   繁体   中英

How to change the style of an element when clicked in React

Im trying to figure out how to change the color style of a checkbox when clicked on in react. It should also toggle back to the old color when clicked again.

function handleClick() { DO SOMETHING HERE TOGGLE THE FILL COLOR }

<CheckCircle onClick={handleClick} style={{ fill: colors.orange }} />

You can use a state for this.

Define the state in your component:

const [clicked, setClicked] = useState(false)

The handleClick funtion would look like this:

function handleClick() {
    setClicked(!clicked);
}

Finally use the clicked variable to adjust your style. Maybe something like this:

<CheckCircle onClick={handleClick} style={{ fill: clicked ? colors.orange : colors.red }} />
const [isChecked, setIsChecked] = useState(true) function handleOnClick() { setIsChecked(prevState => !prevState) } return <CheckCircle onClick={handleOnClick} style={{ fill: isChecked ? colors.orange : OTHER_COLOR }} />

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