Javascript 更新循环中的属性值-Reactjs

Javascript 更新循环中的属性值-Reactjs,javascript,reactjs,Javascript,Reactjs,我试图在react组件的一个循环中,使图像从左到写,从右到左无限地滑动 我无法更改“样式”属性的“左”属性 下面是相关的代码 let lastRight = 0; let multiplier = 1; const images = [One, Two, Three, Four]; class ImageStream extends Component { state = { position: [0, 640, 1280, 1920] }; changeLeft(

我试图在react组件的一个循环中,使图像从左到写,从右到左无限地滑动

我无法更改“样式”属性的“左”属性

下面是相关的代码

let lastRight = 0;
let multiplier = 1;
const images = [One, Two, Three, Four];

class ImageStream extends Component {

  state = {
      position: [0, 640, 1280, 1920]
  };

  changeLeft() {
    if (lastRight > 2000) {
      multiplier = -1;
    } else if (lastRight < -600) {
      multiplier = 1;
    }

    for (let i = 0; i < this.state.position.length; i++) {
      this.state.position[i] = (this.state.position[i] + (multiplier * 1));
      lastRight = this.state.position[i];
    }
  }

  componentDidMount() {
    this.intervalID = setInterval(this.changeLeft.bind(this), 200);
  }

  componentWillUnmount() {
    // use intervalId from the state to clear the interval
    clearInterval(this.intervalId);
  }

  renderImage(imageUrl, index) {
    return (
      <img
        src={imageUrl}
        style={{ left: this.state.position[index] }}
        key={index + "_image"}
      />
    );
  }

  render() {
    return (
      <div id="image-scroll" className="mt-4">
        {images.map((imageUrl, index) => this.renderImage(imageUrl, index))}
      </div>
    );
  }
}

export default ImageStream;
设lastRight=0;
设乘数=1;
常量图像=[1,2,3,4];
类ImageStream扩展组件{
状态={
位置:[064012801920]
};
changeLeft(){
如果(lastRight>2000){
乘数=-1;
}否则如果(lastRight<-600){
乘数=1;
}
for(设i=0;ithis.renderImage(imageUrl,index))}
);
}
}
导出默认图像流;
我所期望的是图像的style属性的left属性会发生变化,因为位置数组会定期变化

我是个新手,很想知道我是否做得不对


提前感谢您的调查

您没有使用
设置状态
来更改
状态
,还调整了一些数字和CSS来运行。一定要去看看

设lastRight=0;
设乘数=1;
常量图像=[“一”、“二”、“三”、“四”];
类ImageStream扩展了React.Component{
状态={
位置:[064012801920]
};
changeLeft(){
如果(lastRight>2000){
乘数=-1;
}否则如果(lastRight<-600){
乘数=1;
}
让posArr=[…this.state.position]
for(设i=0;ithis.renderImage(imageUrl,index))}
);
}
}
//渲染它
ReactDOM.render(
,
document.getElementById(“react”)
);
img{位置:相对;宽度:100px;高度:100px;轮廓:1px纯蓝色;}


你知道什么是状态突变以及为什么不应该这样做吗?是的,使它不可变