Javascript 如何向道具添加其他图像并在单击时更改它们
你好,我正在尝试向我的图像道具添加第二张图像,并在单击时更改它们。有什么建议吗?如何解决?这是我的箱子Javascript 如何向道具添加其他图像并在单击时更改它们,javascript,reactjs,properties,ecmascript-6,Javascript,Reactjs,Properties,Ecmascript 6,你好,我正在尝试向我的图像道具添加第二张图像,并在单击时更改它们。有什么建议吗?如何解决?这是我的箱子 您的图像src需要监听的是状态,而不是道具。道具是不可变的,状态是可变的。下面是一个如何做到这一点的示例 import React from 'react' import { render } from 'react-dom' import { CSSTransitionGroup } from 'react-transition-group' class FadeImage extends
您的图像
src
需要监听的是状态
,而不是道具
。道具是不可变的,状态是可变的。下面是一个如何做到这一点的示例
import React from 'react'
import { render } from 'react-dom'
import { CSSTransitionGroup } from 'react-transition-group'
class FadeImage extends React.Component
{
constructor(props, context, images)
{
super(props);
this.state = {
index: 0,
imageClass: 'image'
};
this.fadeImage = this.fadeImage.bind(this);
}
fadeImage(e)
{
e.preventDefault();
var s = {
index: (this.state.index + 1) % this.props.images.length
};
if (this.state.imageClass === 'image')
{
s.imageClass = "image-loaded";
}
else
{
s.imageClass = "image";
}
this.setState(s);
console.log('clicked');
}
render()
{
return (
<div>
<a href="#" onClick={this.fadeImage}>Change Me!</a>
<img src={this.props.images[this.state.index]} />
</div>
)
}
}
render(<FadeImage images={['http://via.placeholder.com/350x150', 'http://via.placeholder.com/350x151']} />, document.querySelector('#app'))
从“React”导入React
从'react dom'导入{render}
从“反应转换组”导入{CSSTransitionGroup}
类FadeImage扩展了React.Component
{
构造器(道具、上下文、图像)
{
超级(道具);
此.state={
索引:0,
imageClass:“图像”
};
this.fadeImage=this.fadeImage.bind(this);
}
法代迈格(e)
{
e、 预防默认值();
变量s={
索引:(this.state.index+1)%this.props.images.length
};
if(this.state.imageClass=='image')
{
s、 imageClass=“已加载图像”;
}
其他的
{
s、 imageClass=“image”;
}
本.设定状态;
console.log('clicked');
}
render()
{
返回(
)
}
}
render(,document.querySelector('#app'))
请注意,在道具中保留图像路径是非常好的。但您确实需要有一个状态为的当前图像索引。此外,无需多次调用
setState
。您可以将更新作为一个对象的一部分进行准备,并同时介绍所有更新。您需要将一组图像作为道具传递
render(<FadeImage images={["http://via.placeholder.com/350x150", "http://via.placeholder.com/350x151"]} />, document.querySelector('#app'))
如果能成功的话
是的,问题是如何:/问题是我必须混合状态和道具,但我真的不知道如何
this.setState({
index: (this.state.index +1) % this.props.images.length
});