React 教程第四篇 —— 组件事件

前端之家收集整理的这篇文章主要介绍了React 教程第四篇 —— 组件事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

事件和 ref

事件可以直接写到 DOM 节点,然后通过 ref 来获取 DOM 节点

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3.  
  4. class Component1 extends React.Component{
  5. focusHandler(){
  6. this.refs.name.focus();
  7. }
  8. render(){
  9. return (
  10. <div>
  11. <input type="text" name="name" placeholder="" ref="name"/>
  12. <input type="button" name="" value="focus" onClick={this.focusHandler} />
  13. </div>
  14. );
  15. }
  16. };
  17.  
  18. ReactDOM.render(<Component1/>,document.getElementById('div1'));

效果预览

事件对象 —— event

React 在事件方法调用上默认会传一个形参events,该对象是一个合成事件,所以不需要担心浏览器兼容的问题。

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3.  
  4. class Component1 extends React.Component{
  5. submit(e){
  6. e.target.style.color = 'red'
  7. }
  8. render(){
  9. return <input type="button" value="submit" onClick={this.submit}/>
  10. }
  11. }
  12.  
  13. ReactDOM.render(
  14. <Component1 />,document.getElementById('app')
  15. )

事件 —— this 指针

在所有的事件当中,首先都要弄明白 this 指向哪里。而 React 事件中(如上面的案例)默认的 this 都是 undefined,为了 this 指针能正确指回组件对象本身,通常可以用下面几种方法

事件定义使用箭头函数

  1. class Component1 extends React.Component{
  2. submit = (e) => {
  3. console.log(this)
  4. e.target.style.color = 'red'
  5. }
  6. render(){
  7. return <input type="button" value="submit" onClick={this.submit}/>
  8. }
  9. }

事件调用时使用用箭头函数

  1. class Component1 extends React.Component{
  2. submit(e){
  3. console.log(this)
  4. e.target.style.color = 'red'
  5. }
  6. render(){
  7. return <input type="button" value="submit" onClick={(e) => this.submit(e)}/>
  8. }
  9. }

构造函数中使用 bind

  1. class Component1 extends React.Component{
  2. constructor(props){
  3. super(props)
  4. this.submit = this.submit.bind(this);
  5. }
  6. submit(e){
  7. console.log(this)
  8. e.target.style.color = 'red'
  9. }
  10. render(){
  11. return <input type="button" value="submit" onClick={this.submit}/>
  12. }
  13. }

事件调用时用 bind

  1. class Component1 extends React.Component{
  2. submit(e){
  3. console.log(this)
  4. e.target.style.color = 'red'
  5. }
  6. render(){
  7. return <input type="button" value="submit" onClick={this.submit.bind(this)}/>
  8. }
  9. }

事件传参数

事件调用时使用用箭头函数

  1. class Component1 extends React.Component{
  2. submit(e,n){
  3. console.log(this,n)
  4. e.target.style.color = 'red'
  5. }
  6. render(){
  7. return <input type="button" value="submit" onClick={(e) => this.submit(e,100)}/>
  8. }
  9. }

事件调用时用 bind

  1. submit(n,e){
  2. console.log(n)
  3. e.target.style.color = 'red'
  4. }
  5. render(){
  6. return <input type="button" value="submit" onClick={this.submit.bind(this,20)}/>
  7. }
  8. }

猜你在找的React相关文章