zoukankan      html  css  js  c++  java
  • react绑定this另一种方法

    代码如下:

    import React from 'react';
    class Component extends React.Component{
    constructor(props){
    super(props);
    this.state={
    name : 'Rosen',
    age : 18
    }
    this.handleClick = this.handleClick.bind(this);
    }
    handleClick(){
    this.setState({
    age : this.state.age + 1
    });
    }
    onValueChange(e){
    this.setState({
    age : e.target.value
    });
    }
    render(){
    return (
    <div>
    <h1>I am {this.state.name}</h1>
    <p>I am {this.state.age} years old!</p>
    <button onClick={this.handleClick}>加一岁</button>
    <input type="text" onChange={(e) => {this.onValueChange(e)}}/>
    </div>
    );
    }
    }

    function App() {
    return (
    <div className="App">
    <Component/>
    </div>
    );
    }

    export default App;
    这里handleClick方法绑定到button上this.handleClick要想有效必须在constructor中设置this.handleClick = this.handleClick.bind(this),绑定this才可以正常使用否则会报错,也可以如下的
    代码实现绑定:
    import React from 'react';
    class Component extends React.Component{
    constructor(props){
    super(props);
    this.state={
    name : 'Rosen',
    age : 18
    }
    // this.handleClick = this.handleClick.bind(this)
    }
    handleClick(){
    this.setState({
    age : this.state.age + 1
    });
    }
    onValueChange(e){
    this.setState({
    age : e.target.value
    });
    }
    render(){
    return (
    <div>
    <h1>I am {this.state.name}</h1>
    <p>I am {this.state.age} years old!</p>
    <button onClick={ () =>{this.handleClick()}}>加一岁</button>
    <input type="text" onChange={(e) => {this.onValueChange(e)}}/>
    </div>
    );
    }
    }

    function App() {
    return (
    <div className="App">
    <Component/>
    </div>
    );
    }

    export default App;
    通过箭头函数执行该方法就不用绑定this了
     react 子组件通过props接收父组件传递的数据,子组件改变父组件的数据,也是通过props接收的方法绑定到props来出发父组件的数据改变。
  • 相关阅读:
    WF4.0 自定义CodeActivity与Bookmark<第三篇>
    WF4 常用类<第二篇>
    WF4.0 Activities<第一篇>
    WWF3常用类 <第十一篇>
    WWF3XOML方式创建和启动工作流 <第十篇>
    element-ui表格显示html格式
    tail -f 加过滤功能
    vue 遇到防盗链 img显示不出来
    python No module named 'urlparse'
    grep awk 查看nginx日志中所有访问的ip并 去重
  • 原文地址:https://www.cnblogs.com/zhx119/p/10889711.html
Copyright © 2011-2022 走看看