如何解决反应 useState 以返回具有两种不同条件的假图像
当两个按钮为 false 时,它们返回相同的图像,但它们彼此相邻,如何使两种状态的 test3 图像相等,而不必插入另一张图像?
const [b1State,setB1State] = useState(false);
const [b2State,setB2State] = useState(false);
<button onClick={() => {setB1State(!b1State)}}>Test1</button>
<button onClick={() => {setB2State(!b2State)}}>Test2</button>
{b1State ? <img src={test1} alt="" /> : <img src={test3} alt="" />}
{b2State ? <img src={test2} alt="" /> : <img src={test3} alt="" />}
问题是当两个按钮都为真时,它把一张图片放在上面,一张放在下面,我相信当一个是真的另一个应该是假的。
解决方法
2 种按钮状态有 4 种可能的组合(0 0,0 1,1 0,1 1) - 因此您需要检查所有这些。
当两者都打开时要显示哪个按钮图像? - 您需要创建一个新的状态变量来存储 lastClicked 按钮。
/* These constants contains image url */
const test1 = "full length apron";
const test2 = "waist apron";
const test3 = "naked";
const [b1State,setB1State] = useState(false);
const [b2State,setB2State] = useState(false);
// last clicked option will be displayed when both of them are "true" - so created a new state
const [lastClicked,setLastClicked] = useState(test1);
return(
<>
<button onClick={() => {setB1State(!b1State); setLastClicked(test1)}}>Test1</button>
<button onClick={() => {setB2State(!b2State); setLastClicked(test2)}}>Test2</button>
{/* when both the button are off - naked guy image appears */}
{ (!b2State && !b1State) && <img src={test3} alt={test3} /> }
{/* when button 1 is on and 2 is off - full length apron image appears */}
{ (b1State && !b2State) && <img src={test1} alt={test1} /> }
{/* when button 2 is on and 1 is off - waist apron image appears */}
{ (b2State && !b1State) && <img src={test2} alt={test2} /> }
{/* when both the buttons are on - last button click image appears */}
{ (b1State && b2State) && <img src={lastClicked} alt={lastClicked} /> }
</>
);
,
您可以使用 Set 来确保图像 src
被包含一次。创建 Set 后,将其展开回数组,并使用 Array.map()
进行渲染:
const { useState,useMemo } = React
const test1 = 'https://picsum.photos/id/237/100'
const test2 = 'https://picsum.photos/id/1003/100'
const test3 = 'https://picsum.photos/id/1024/100'
const Demo = () => {
const [b1State,setB1State] = useState(false);
const [b2State,setB2State] = useState(false);
// create the unique array of images using a Set
const images = useMemo(() => [...new Set([
b1State ? test1 : test3,b2State ? test2 : test3,])],[b1State,b2State])
return (
<div>
<button onClick={() => {setB1State(!b1State)}}>Test1</button>
<button onClick={() => {setB2State(!b2State)}}>Test2</button>
<br />
{images.map(src => ( // render the array
<img key={src} src={src} alt="" />
))}
</div>
)
}
ReactDOM.render(
<Demo />,root
)
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
您可以将此条件渲染单独用于 img3
{(!b1State && !b2State) && <div>show img3</div>}
{b1State && <div>show img1</div>}
{b2State && <div>show img2</div>}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。