[英]Ternary operation not working on button click in reactJS?
I am conditionally rendering a button so when it is clicked, the button changes from a play to pause.我有条件地渲染一个按钮,所以当它被点击时,按钮从播放变为暂停。 I am doing this via ternary operation, however, when the button is clicked it does not change.
我是通过三元操作来做到这一点的,但是,当单击按钮时,它不会改变。 Here is my code:
这是我的代码:
...
const isOn = true;
...
return(
...
{isOn ? (<Button className="icon" color="info" type="submit" onClick={startMe}><i className="playicon"/></Button>) : (<Button className="icon" color="info" type="submit" onClick={stopMe}><i className="pauseicon"/></Button>)}
...
)
I don't really understand why this isn't working.我真的不明白为什么这不起作用。 If I manually set
isOn
to false
the button changes but if I click it does not.如果我手动将
isOn
设置为false
按钮会改变,但如果我点击它不会。
You've forgotten to wrap your whole JSX elements in a parent element while using the ternary operator.在使用三元运算符时,您忘记将整个JSX元素包装在一个父元素中。
So, wrap them in a fragment
<></>
element or React.Fragment
因此,将它们包装在
fragment
<></>
元素或React.Fragment
return (
<>
{
// your ternary logics here
}
</>
)
Or:或者:
import React, {Fragment} from 'react';
// rest of the codes ...
return (
<Fragment>
{
// your ternary logics here
}
</Fragment>
)
You can't use regular variables like const isOn = true;
你不能使用像
const isOn = true;
这样的常规变量const isOn = true;
because they will not cause a re-render.因为它们不会导致重新渲染。 You need to use state.
您需要使用状态。
const [isOn, setIsOn] = useState(true); // set default to false if you want
const startMe = () => {
setIsOn(true);
}
const stopMe = () => {
setIsOn(false);
}
return(
<>
{isOn
? (<Button className="icon" color="info" type="submit" onClick={startMe}><i className="playicon"/></Button>)
: (<Button className="icon" color="info" type="submit" onClick={stopMe}><i className="pauseicon"/></Button>)
}
</>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.