一个完整的界面,一半是展示,另一半是响应。React 通过将事件处理器绑定到组件上来处理事件(事件触发,更新组件状态,从而重绘)。
让我们看看以下列子
<button class=" sub " onClick = { this.handleClick } > 确定 </button> //或者 React.DOM.button( { calssName : "sub", onClick : this.handleClick }, "确定");
这里大家要了解一下:React 写法上类似 HTML 内联事件处理器属性,但底层并没有使用 HTML 的 onClick 属性(通过事件代理之类的手法)。
React 对各类事件提供了很好的支持,大家可以浏览一下 React 的事件系统
只看不写有点无聊,写点无意义的显示,目的:尝试 stateless 和 es6 重构React写法,试验 React事件处理和了解 HTML5 拖动。如果大家觉得我写的不对,请留言指正。下面是 js 部分:
/*
* @2016年9月27日21:11:48
* 目的:
* 尝试 stateless 和 es6 重构React写法
* 试验 React事件处理
* 了解 HTML5 拖动
*/
/*Logo模块*/
let Log = ()=>{
return(
<div id="log" draggable="true" onDragStart={drag}>A log</div>
);
}
/*搜索模块*/
let SearchBox = ()=>{
return(
<div id="search" draggable="true" onDragStart={drag}>A SearchBox</div>
);
}
/*新闻模块*/
let NewList = ()=>{
return(
<div id="news" draggable="true" onDragStart={drag}>A NewList</div>
);
}
/*响应onDragStart函数*/
const drag = function(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
/**
* 工具条
* */
class ToolBar extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div>
{this.props.isLog == true? <Log /> : ""}
{this.props.isNewList == true? <NewList/> : ""}
{this.props.isSearchBox == true? <SearchBox/> : ""}
</div>
);
}
}
/*
* 内容界面
* */
class Plant extends React.Component {
constructor(props) {
super(props);
this.state ={
isLog: false,
isNewList:false,
isSearchBox:false,
};
this.drop = this.drop.bind(this);
}
allowDrop(ev)
{
ev.preventDefault();
}
drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
switch (data){
case 'log' : this.setState({isLog: true});break;
case 'search' : this.setState({isSearchBox: true});break;
case 'news' : this.setState({isNewList: true});break;
}
ev.target.appendChild(document.getElementById(data));
}
render() {
return(
<div id="box" style={{border:'1px solid red',width:200,height:300}} onDrop={this.drop} onDragOver={this.allowDrop}>
<p>{this.state.isLog == true? "添加了 logo 模块" : ""}</p>
<p>{this.state.isNewList == true? "添加了 新闻 模块" : ""}</p>
<p>{this.state.isSearchBox == true? "添加了 搜索 模块" : ""}</p>
</div>
);
}
}
//容器
let Content = (tools)=>{
return(
<div>
<ToolBar {...tools}/>
<Plant/>
</div>
);
}
//工具条内容
const tools = {isLog: true, isNewList:true, isSearchBox:true};
ReactDOM.render(
<Content {...tools}/>,
document.getElementById('example')
);
html部分:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react.min.js"></script>
<script src="http://static.runoob.com/assets/react/react-0.14.7/build/react-dom.min.js"></script>
<script src="http://static.runoob.com/assets/react/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel" src="event.js"></script>
</body>
</html>