根据 React 功能组件中的状态变量有条件地设置 className
Posted
技术标签:
【中文标题】根据 React 功能组件中的状态变量有条件地设置 className【英文标题】:Conditionally setting className based on a state variable in a React functional component 【发布时间】:2020-10-15 07:37:43 【问题描述】:我正在尝试根据该元素是否存在于状态来更改按钮的外观。这是一个多选选择。所以调用了setAnswer,它调用了addAnswer。然后,我想根据元素是否处于状态来设置 className,但我没有得到它。
question.values.map(answer =>
return <button className="buttons" key=answer onClick=() => addAnswer(answer)>
answer</button>
)
const addAnswer = (answer) =>
let indexAnswer = answers.indexOf(answer)
if (indexAnswer > -1)
setAnswer((answers) => answers.filter((a) =>
return a != answer ))
else setAnswer([...answers, answer])
;
【问题讨论】:
我想建议您也许有一个问题的 id,它可能会更容易查找、选择它们并进行比较, 【参考方案1】:你可以像这样有条件地设置一个类
question.values.map(answer =>
return (<button
className=answers.indexOf(answer) === -1 ? 'class1' : 'class2'
key=answer
onClick=() => addAnswer(answer)
>
answer
</button> );
)
【讨论】:
谢谢悉达多!【参考方案2】:clsx 是完美的选择。您可以有条件地设置一个或多个在条件为真时使用的类名。
这是我制作的一个真实有效的 sn-p,也可以在这里找到 https://codesandbox.io/s/gracious-sound-2d5fr?file=/src/App.js
import React from "react";
import "./styles.css";
import clsx from "clsx";
import createUseStyles from "react-jss";
// Create your Styles. Remember, since React-JSS uses the default preset,
// most plugins are available without further configuration needed.
const useStyles = createUseStyles(
answer1: color: "red" ,
answer2: color: "green" ,
answer3: color: "yellow"
);
export default function App()
const classes = useStyles();
const questions =
values: [
type: 1, value: "aaaa" ,
type: 2, value: "bbbb" ,
type: 3, value: "cccc" ,
type: 1, value: "dddd" ,
type: 2, value: "eeee" ,
type: 3, value: "ffff"
]
;
return (
<div className="App">
questions.values.map(answer => (
<p>
<button
className=clsx(classes.always,
[classes.answer1]: answer.type === 1,
[classes.answer2]: answer.type === 2,
[classes.answer3]: answer.type === 3
)
>
answer.value
</button>
</p>
))
</div>
);
有关 clsx 的更多信息,请参阅此处的示例 Understanding usage of clsx in React
或者,您可以通过逻辑确定类名并将其设置在这样的变量中
const getClassName = ()=>
switch(answer)
case(1): return "class1"
case(2): return "class2"
...
render(
/// within the map function
< className=getClassName() />
)
【讨论】:
以上是关于根据 React 功能组件中的状态变量有条件地设置 className的主要内容,如果未能解决你的问题,请参考以下文章