实现的功能:在点击按钮,显示图片,如图所示:
代码还在不断的完善和更新中,代码详见:https://github.com/EmilyQiRabbit/ReactBasicPicturesViewer
核心代码(HTML文件中body标签内代码):
<body>
<h1>Basic Example</h1>
<div id="viewerContainer"></div>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="react/browser.min.js"></script>
<!-- <script src="react/react-with-addons.js"></script> -->
<script type="text/babel">
(function(){
// 遮盖层(with img)
var BlockModule = React.createClass({
getInitialState: function() {
return { ifShowStyle:this.props.ifShowStyle };
},
componentWillReceiveProps : function(nextProps){
this.setState( { ifShowStyle : nextProps.ifShowStyle } );
},
imgDisappearHandler : function(){
this.setState( { ifShowStyle:{ display: "none" } } );
},
render: function() {
return (
<div className="blockDiv" style={this.state.ifShowStyle}>
<ImgModule imgUrl={this.props.imgUrl}></ImgModule>
<div onClick={this.imgDisappearHandler}></div>
</div>
)
}
});
// 图片
var ImgModule = React.createClass({
render: function() {
return <img src = {this.props.imgUrl}/>;
}
});
var EventElement = React.createClass({
getInitialState: function() {
return { ifShowStyle: { display: "none" } };
},
imgEmergeHandler : function(){
this.setState( { ifShowStyle:{ display: "block" } } );
},
render : function(){
return (
<div>
<BlockModule imgUrl={this.props.imgUrl} ifShowStyle={this.state.ifShowStyle}></BlockModule>
<button className={this.props.ElementButtonClass} onClick={this.imgEmergeHandler}>click To Show Image</button>
</div>
)
}
});
ReactDOM.render(
<EventElement imgUrl="imgs/test.jpg" ElementButtonClass="btnclass">click To Show Image</EventElement>,
/* imgUrl:图片src ;
ElementClass:按钮样式的类名 */
document.getElementById('viewerContainer')
);
})()
</script>
</body>
主要知识点:
1、React.createClass
2、state, getInitialState()
3、props
4、onClick事件
5、生命周期函数componentWillReceiveProps