您的位置:首页 > Web前端 > React

React入门Today.5(事件处理与条件渲染)

2020-02-17 03:10 429 查看

事件处理

  • React 事件的命名采用小驼峰式(camelCase),而不是纯小写。
  • JSX中事件处理需要传入一个函数,而不是一个字符串。
  • HTML写法
<button onclick="click1()">点击我</button>
  • JSX写法
<button onclick={click1}>点击我</button>

  • 在React中的另一个不同点是不能反悔false直接阻止其默认行为,而要使用
    preventDefault
  • 例如下面这个程序,阻止页面跳转
  • HTML
<body>
<a href="http://www.lqxlhw.tk/" οnclick="console.log("你不能打开这个页面");return false">点击我</a>
</body>
  • React
<body>
<div id="box_event"></div>
<script type="text/babel">
function Click1(){
function open1(e){
e.preventDefault();
console.log('你不能打开这个界面');
}
return(
<a href="http://www.lqxlhw.tk/" onClick={open1}>点击我</a>
);
}
ReactDOM.render(
<Click1 />,
document.getElementById("box_event")
);
</script>

</body>
  • 在React中
    onClick
    的第二个首字母是大写,而在html中是小写,如果不注意这一点会直接跳转到页面。
  • 上面的两种方式效果相同,不能跳转到标签
    a
    中的界面。
  • 当使用ES6 class的语法定义一个组件的时候,通常的做法是将事件处理声明作为class中的方法。

例如

<body>
<div id="box_event"></div>
<script type="text/babel">
class Click2 extends React.Component{
constructor(props){
super(props);
this.state={onf:true};
{/*需要手动绑定this,bind方法生成了一个新的函数,称为绑定函数,
它的this关键字会变成传入的值
直接将当前组件(或者叫类)的实例与函数绑定。
bind在回调函数中经常使用,为了在回调中使用“this”,绑定是必不可少的
*/}
this.handleClick=this.handleClick.bind(this);
}
handleClick(){
{/*
用小括号包含大括号则是对象的定义,而非函数主体
*/}
this.setState(state=>({
onf:!state.onf
}));
}
render(){
{/*用onf返回的值改变当前的状态是开还是关*/}
return(
<button onClick={this.handleClick}>
{this.state.onf? "开":"关"}
</button>
);
}
}

ReactDOM.render(
<Click2 />,
document.getElementById("box_event")
);
</script>

</body>
  • 运行结果


点击按钮,状态文字会变成关,点击一次改变一次当前的状态。在class的方法中不会默认绑定

this
,如果忘记了将
this.handleClick
传入
onClick
,会导致调用这个函数中的
this
underfind

向事件函数传递参数

  • 以下两种方式是等价的,分别通过箭头函数和Function.prototype.bind来实现。
    例如循环中,传递参数,若id是要删除的哪行的ID:
  • <button onClick{(e)=>this.deleteRow(id,e)}>删除本行</button>
    <button onClick{(this.deleteRow.bind(this,id)}>删除本行</button>
  • 通过箭头函数,事件对象通过显示的传递,而通过bind方式,事件对象及更多的参数都会被隐式传递
  • 点赞
  • 收藏
  • 分享
  • 文章举报
over.here 发布了5 篇原创文章 · 获赞 0 · 访问量 71 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: