英文:
How to make conditional props in Bootstrap Button Group in ReactJS
问题
有了下面这个 useState
:
const [orderStandard, setOrderStandard] = useState("total");
根据 orderStandard
的值,我想要传递 props。
这段代码是使用 ReactJS 的 BootStrap 中的 ButtonGroup
:
<ButtonGroup
style={{
height: 35,
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<Button
id="order-button"
variant="light"
style={{ width: 80 }}
active
onClick={() => setOrderStandard("total")}
>
上面,在 Button 的 props 中,active
会使按钮被选中。
所以我将其做成条件语句,如下所示:
<Button
id="order-button"
variant="light"
style={{ width: 80 }}
{...(orderStandard === "total" ? active : null)}
onClick={() => setOrderStandard("total")}
>
然而,这会抛出错误。错误信息是:'...' expected.ts(1005)
。
所以我使用了 ...
,像这样:
<Button
id="order-button"
variant="light"
style={{ width: 80 }}
{...(orderStandard === "total" ? { active } : null)}
onClick={() => setOrderStandard("total")}
>
但当我写了上面的代码时,它说 active
props 未定义。
如何解决呢?
英文:
I have useState
as below:
const [orderStandard, setOrderStandard] = useState("total");
And according to the value of orderStandard
, I want to give props.
This below code is ButtonGroup
of BootStrap with ReactJS.
https://react-bootstrap.github.io/components/button-group/#button-toolbar-props
<ButtonGroup
style={{
height: 35,
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<Button
id="order-button"
variant="light"
style={{ width: 80 }}
active
onClick={() => setOrderStandard("total")}
>
above, among props of Button, active
make button being selected.
So I make it conditional as below.
However it throws error. Error says: '...' expected.ts(1005)
So I make with ...
<Button
id="order-button"
variant="light"
style={{ width: 80 }}
{...(orderStandard == "total" ? active : null)}
onClick={() => setOrderStandard("total")}
>
But when I wrote code above, It says active
props is not defined.
How can I make it?
答案1
得分: 1
试试这样写:
active={orderStandard === "total" ? true : false)}
如果他返回 false
,你可以尝试使用 null
和 undefined
。
英文:
Try it like this:
active={orderStandard == "total" ? true : false)}
If he scolds false
you can try with null
and undefined
答案2
得分: 1
你出现'active' 未定义
的错误是因为你尝试将active
作为变量使用,而不是将其作为Button
的属性使用。
尝试使用这个代替:
<Button
id="order-button"
variant="light"
style={{ width: 80 }}
active={orderStandard == "total"}
onClick={() => setOrderStandard("total")}
>
英文:
You're getting 'active' is not defined
because you're trying to use active
as a variable instead of using it as an attribute of Button
.
Try this instead
<Button
id="order-button"
variant="light"
style={{ width: 80 }}
active={orderStandard == "total"}
onClick={() => setOrderStandard("total")}
>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论