已写的代码如下:
import React, { useRef } from 'react';
import { Grid } from 'antd-mobile';
// import './style.css';
export default () => {
// 获取元素节点
let color1 = useRef();
let color2 = useRef();
let color3 = useRef();
let color4 = useRef();
// 触发点击事件改变样式
function touchstart1() {
color1.current.style.backgroundColor = 'gray';
}
function touchend1() {
color1.current.style.backgroundColor = 'white';
}
function touchstart2() {
color2.current.style.backgroundColor = 'gray';
}
function touchend2() {
color2.current.style.backgroundColor = 'white';
}
function touchstart3() {
color3.current.style.backgroundColor = 'gray';
}
function touchend3() {
color3.current.style.backgroundColor = 'white';
}
function touchstart4() {
color4.current.style.backgroundColor = 'gray';
}
function touchend4() {
color4.current.style.backgroundColor = 'white';
}
return (
<div className='grid'>
<Grid columns={2} gap={4}>
<Grid.Item>
<div className='grid-demo-item-block' ref={color1} onTouchStart={() => { touchstart1() }} onTouchEnd={() => { touchend1() }}>
<div className='g'>
<p>家住琶洲</p>
<span>前景可期</span>
</div>
<img src={require(`./1.jpg`)} alt='' />
</div>
</Grid.Item>
<Grid.Item>
<div className='grid-demo-item-block' ref={color2} onTouchStart={() => { touchstart2() }} onTouchEnd={() => { touchend2() }}>
<div className='g'>
<p>家住琶洲</p>
<span>前景可期</span>
</div>
<img src={require(`./2.jpg`)} alt='' />
</div>
</Grid.Item>
<Grid.Item>
<div className='grid-demo-item-block' ref={color3} onTouchStart={() => { touchstart3() }} onTouchEnd={() => { touchend3() }}>
<div className='g'>
<p>家住琶洲</p>
<span>前景可期</span>
</div>
<img src={require(`./3.jpg`)} alt='' />
</div>
</Grid.Item>
<Grid.Item>
<div className='grid-demo-item-block' ref={color4} onTouchStart={() => { touchstart4() }} onTouchEnd={() => { touchend4() }}>
<div className='g'>
<p>家住琶洲</p>
<span>前景可期</span>
</div>
<img src={require(`./4.jpg`)} alt='' />
</div>
</Grid.Item>
</Grid>
</div>
)
};
希望实现以下效果:对以下四个盒子其中一个盒子手指按压后,将该盒子的背景色变成灰色,手指松开后背景色变回白色
请问如何才能让以上关于四项手指按压事件的代码更简洁?