我正在使用 tailwind CSS 制作一个 React 应用程序,并尝试在按钮上实现一个 onClick 函数,该函数将更改所述按钮的颜色。但是,样式存储在 Tailwind 的类名中,我正在尝试使用反引号和 useState 钩子。我目前收到“'状态'未定义”的错误
代码附在下面,非常感谢。
import { Link } from 'react-router-dom';
function Column(props){
const [color, setColor] = useState({color:'yellow-200'})
const onClic=()=>{
setColor('grey-200')
}
return (
<button className={`w-300 hover:bg-yellow-100 shadow-xl p-6 max-w-xs mr-1.5 ml-4 mt-4 mb-4 bg-${state.color} rounded-xl shadow-md flex items-center space-x-4`} >
<div class="flex-shrink-0">
<img class="h-12 w-12" src={props.img} alt={props.name}/>
</div>
<div>
<div class="text-xl font-medium text-black">{props.name}</div>
<p class="text-gray-500">{props.price}</p>
</div>
</button>
);
};
export default Column;
答案 0 :(得分:2)
有了函数式组件和钩子,就不需要访问state.color
,你有一个状态值叫做color
,可以直接使用。
<button
className={`w-300 hover:bg-yellow-100 shadow-xl p-6 max-w-xs mr-1.5 ml-4 mt-4 mb-4 bg-${color} rounded-xl shadow-md flex items-center space-x-4`}
>
此外,您的按钮需要一个 onClick
来处理您的状态更新。
const handleClick = () => {
setColor("somecolor");
}
<button
className={`w-300 hover:bg-yellow-100 shadow-xl p-6 max-w-xs mr-1.5 ml-4 mt-4 mb-4 bg-${color} rounded-xl shadow-md flex items-center space-x-4`}
onClick={handleClick}
>
答案 1 :(得分:0)
const [color, setColor] = useState({color:'yellow-200'})
这会在当前范围内创建一个名为 color
的变量(还有一个名为 setColor
的变量,用于更新状态)。
它不会创建具有 state
属性的名为 color
的变量。
直接访问 color
。 state
未定义,因为您没有定义它。