4
我正在做輪播,並且狀態更新時我的內聯翻譯不起作用。狀態更新時樣式不會更新
這裏是我的組件:
class Carousel extends React.Component {
constructor() {
super();
this.state = {
hover: false,
containers: 0,
imgList: [],
translate: 0,
fullWidth: 0,
width: 0
};
this.height = 400;
this.moveLeft = this.moveLeft.bind(this);
this.moveRight = this.moveRight.bind(this);
}
componentWillMount() {
const imgList = [
'http://2.bp.blogspot.com/--r4xdyuNQCQ/UAu7wFbDfDI/AAAAAAAAIUg/qtlUyQ8XKYM/s1600/Hdhut.blogspot.com+%2811%29.jpeg',
'http://4.bp.blogspot.com/-BJaTlb_j_Fw/TwK1agDhf-I/AAAAAAAABb0/nvYDoNoSCPk/s1600/singapore-wallpaper-2-778799.jpg',
'http://greatinspire.com/wp-content/uploads/2016/06/Most-Beautiful-Places-In-Japan-9.jpg',
'http://www.thetravelexperts.net/gallery/places-to-visit-in-france/9_eiffel_tower.jpg'
];
this.setState({ imgList: [...imgList] });
}
moveLeft() {
const { translate, fullWidth } = this.state;
this.setState({ translate: translate + fullWidth });
}
moveRight() {
const { translate, fullWidth } = this.state;
this.setState({ translate: translate - fullWidth });
}
componentDidMount() {
const fullWidth = document.body.clientWidth;
const width = fullWidth/2;
this.setState({ fullWidth, width });
}
render() {
const { imgList, translate, fullWidth, width } = this.state;
return (
<nav className={style.wrapper} style={{ height: this.height }}>
<div className={style.arrows} style={{ width: `${fullWidth}px` }}>
<div className={style['arrow-left']} onClick={this.moveLeft} />
<div className={style['arrow-right']} onClick={this.moveRight} />
</div>
<ul
className={style.ul}
style={{ transform: `translateX(${translate})` }}
>
{imgList.length > 0 &&
imgList.map(src =>
<li
key={src}
className={style.li}
style={{ width: `${width}px` }}
>
<figure className={style.figure}>
<img className={style.img} width={width} src={src} />
</figure>
</li>
)}
</ul>
</nav>
);
}
}
export default Carousel;
此代碼基本上把我的UI元素和翻譯爲左,右,以顯示我的圖片。 我試圖在moveRight和moveLeft的最後使用this.forceUpdate,但它不起作用。
出了什麼問題?
是你的變量以及更新?渲染方法是否被再次調用? (嘗試用控制檯日誌來真正知道問題在哪裏,它可能是一個或另一個) – Nevosis
我的變量已更新,我已記錄 –
在您的渲染方法?看起來很奇怪,如果你的渲染再次被調用並且你的變量設置的很好。 – Nevosis