javascript - 有没有办法简化 React.js 中状态内的一长串代码
问题描述
我有一个图像滑块{Carousel},它有自己的文本,文本从左右滑入。我通过在间隔内使用 if 语句在状态中添加每个效果来实现这一点,但是代码真的很长,必须有一种方法可以用更少的代码来实现这一点。提前谢谢。
状态
class Showcase extends Component {
constructor(props) {
super(props);
this.state = {};
}
ComponentDidMount
defaultState() {
const arr = [
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine"
];
const dir = ["Right", "Left"];
const obj = { width: 0 };
for (let i = 0; i < dir.length; i++) {
for (let k = 0; k < arr.length; k++) {
obj[`animate${dir[i]}${arr[k]}`] = "";
}
}
return obj;
}
componentDidMount() {
console.log(this.state);
console.log(this.defaultState());
this.sliderwidth();
this.showAnime();
const wow = new WOW();
wow.init();
}
方法
showAnime = () => {
const arr = [
"One",
"Two",
"Three",
"Four",
"Five",
"Six",
"Seven",
"Eight",
"Nine"
];
let counter = 0;
setInterval(() => {
counter++;
if (counter === 9) {
this.setState(this.defaultState());
} else {
const state = this.state;
state[
`animateLeft${arr[counter]}`
] = `animated fadeInLeftBig delay-${arr[counter].toLowerCase()}`;
state[
`animateRight${arr[counter]}`
] = `animated fadeInRightBig delay-${arr[counter].toLowerCase()}`;
this.setState(state);
}
}, 7000);
console.log(this.state);
};
sliderwidth = () => {
setInterval(() => {
const slide = this.state.width + 100;
this.state.width === 800
? this.setState({
width: 0
})
: this.setState({
width: slide
});
}, 7000);
};
解决方案
好的,这里是代码。简单的想法是创建一个数字数组,例如['One','Two'...]
.
创建默认状态的方法
function defaultState(){
const arr = ['One','Two','Three','Four','Five','Six','Seven','Eight','Nine'];
const dir = ['Right','Left']
const obj = {width:0}
for(let i = 0;i<dir.length;i++){
for(let k = 0;k<arr.length;k++){
obj[`animate${dir[i]}${arr[k]}`] = '';
}
}
return obj;
}
console.log(defaultState())
显示胺功能
showAnime = () => {
const arr = ['One','Two','Three','Four','Five','Six','Seven','Eight','Nine'];
let counter = 0;
setInterval(() => {
counter++;
if(counter === 9){
this.setState(defaultState());
}
else{
const state = this.state;
state[`animateLeft${arr[counter]}`] = `animated fadeInLeftBig delay-${arr[counter].toLowerCase()}`
state[`animateRight${arr[counter]}`] = `animated fadeInRightBig delay-${arr[counter].toLowerCase()}`
this.setState(state)
}
}, 7000);
};
推荐阅读
- java - 使用 sudo 命令时使用 GUI 使 javafx jar 提示管理员凭据
- java - 注释的参数
- c++ - 从 C++ 中的动态库访问静态类成员
- cassandra - 如何使用 Python 驱动程序在 Cassandra 中导入 CSV?
- amazon-web-services - 是否可以通过 AWS CLI 从 Origin 找到云端分发?
- c - 将二进制文件内容从 STDIN 重定向到 C 程序
- bash - xargs -I {} ls {}* : 无法访问没有这样的文件或目录
- templates - 如何使用机器人框架中的数据驱动程序在单个文件中编写模板化/正常测试
- jquery - 使用 addResource 方法添加资源
- ios - 如何使用另一种自定义类型的子对象将对象保存在 Core Data 中?