在React中触发偶数时移动对象宽度不同的轮播

问题描述

  • 我有一堆想要触发事件的对象。
  • 如果触发了该事件,则所有对象都应向左滑动,直到下一个对象(位于中间的一个对象的右侧)成为下一个对象。
  • 如果多次单击该按钮,则转换将每执行一次,而不会因先前的事件而延迟或中断先前的转换。

所以我的两个问题是:

  1. 如何在React中实现此事件处理程序?
  2. css外观如何才能使其正常工作?
const myBoxes = [
{width: 10,color: "red"},{width: 20,color: "blue"},{width: 50,color: "yellow"},{width: 30,color: "green"},{width: 40,color: "black"}
]

const Boxes = () => {
  const shiftBoxes = (e) => {
     //I dont kNow how to implement this
  }
  return (
    <div>
    <button onClick={shiftBoxes}>Click Me to Shift Boxes to the left by one Box</button>
    <div className="Box-wrapper">
        {myBoxes.map((Box) => (
          <span style={{  
          backgroundColor: Box.color,width:`${Box.width}px`
          }}> </span>
        ))}
    </div>
    </div>
  );
};

ReactDOM.render(
<Boxes/>,document.body)
button {
margin: 10px 0px;}

.Box-wrapper {
border: 2px solid black; 
width: 100%;
height: 60px;
display: flex;
align-content: center;
justify-content: space-between;
}

span {
padding: 20px;
margin: 10px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

解决方法

Use React State to accomplish this by either transforming this component to class based component or use Hooks useState().
Using changeCSS as variable,initialise the state and set it to default as false.
 
    
shiftBoxes(){
     this.setState({changeCSS: true});
  }
return (
    <div>
    <button onClick={shiftBoxes()}>Click Me to Shift Boxes to the left by one Box</button>
    <div className="box-wrapper">
        {myBoxes.map((box) => (
          <span style={this.changeCSS(box)}> </span>
        ))}
    </div>
    </div>
  );
changeCSS(box:any){
if(this.state.changeCSS){
  backgroundColor: box.color,width:`${box.width}px`
  margin-left:-10%;
} else {
backgroundColor: box.color,width:`${box.width}px`enter code here`
}