[英]2 type: radio buttons that change color when clicked React
I want to make a component, where there are two options, and when you select one, the color of the buttons gets switched, currently, I'm trying with Inputs of type: radio, but I would like to know if there is any other way to do it with react.我想制作一个组件,其中有两个选项,当您选择一个时,按钮的颜色会切换,目前,我正在尝试输入类型:radio,但我想知道是否有任何其他方式来做反应。
import React, {useState} from 'react'
function BotonCambioPerfil() {
const [gender, setGender] = React.useState('Famale');
const handleCatChange = () => {
setGender('Male');
};
const handleDogChange = () => {
setGender('Female');
};
return (
<div className='contenedorBotonCambioPerfil'>
<RadioButton
label="Male"
value={gender === 'Male'}
onChange={handleCatChange}
/>
<RadioButton
label="Female"
value={gender === 'Female'}
onChange={handleDogChange}
/>
</div>
)
}
const RadioButton = ({ label, value, onChange }) => {
return (
<label>
<input type="radio" checked={value} onChange={onChange} />
{label}
</label>
);
};
export default BotonCambioPerfil
this example takes a state of gender (default to girl), and sets a const that checks if gender is equal to girl it will return the pink component else it will return a blue component.此示例采用性别状态(默认为女孩),并设置一个 const 来检查性别是否等于女孩,它将返回粉红色组件,否则将返回蓝色组件。 The onclick function changes the state to the gender its not.
onclick 函数将状态更改为非性别。 (girl or boy)
(女孩或男孩)
import React, { useState } from 'react'
export default function App() {
const [ gender , setGender ] = useState("girl")
const changeGender = () => {
if(gender === "girl") {
setGender("boy")
} else setGender("girl")
}
const genderBtn = gender === "girl" ?
<h2 onClick={changeGender} style={{
backgroundColor: "pink",
width: "100px",
padding: "2px",
borderRadius: "100px",
cursor: "pointer",
}}>{gender}</h2>
:
<h2 onClick={changeGender} style={{
backgroundColor: "lightblue",
width: "100px",
padding: "2px",
borderRadius: "100px",
cursor: "pointer",
}}>{gender}</h2>
return (
<div className="App">
<h1>Gender Switch</h1>
{genderBtn}
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.