美文网首页
react事件与数据的双向绑定

react事件与数据的双向绑定

作者: 兔子不打地鼠打代码 | 来源:发表于2018-02-27 20:24 被阅读71次

es5
onClick= {this.changeUserInfo}
es6
onClick= {this.changeUserInfo.bind(this)}]

如何通过onClick动作调用函数传递动作

点击按钮,将state中的age的值改为50

class BodyIndex extends Component {
    constructor(){
        super(); //调用基类的所有的初始化方法
        this.state =  {
            username : "Parry",
            age : 20
        }; //初始化赋值
    }

    changeUserInfo(){
        this.setState({age:50})
    }
    render() {
        return (
            <div>
                <h2>页面的主体内容</h2>
                <p>{this.props.userid} {this.props.username}</p>
                <p>{this.state.age}</p>
                <input type="button" value="提交" onClick={this.changeUserInfo.bind(this)} />
            </div>

        )
    }
}

如何实现子页面向父页面传递参数

在子页面调用父页面的props,用onChange事件来调用函数onChange={this.props.handelChildValueChange}
子页面向父页面传递参数的时候,只能通过事件的形式,调用父页面通过props传过来的参数(这个参数是一个函数,函数还可以接受一个定义好的原生的event参数),触发onChange时,this.setState({age: event.target.value})中的age将变成event的value值

注意es6 的语法

es5和es6构造函数的写法不同

es5this.forceUpdateHandler
es6this.forceUpdateHandler.bind(this)后者调用时绑定onClick={this.changeUserInfo.bind(this,50)}

区别

onChange和onBlur的区别?

相关文章

网友评论

      本文标题:react事件与数据的双向绑定

      本文链接:https://www.haomeiwen.com/subject/sbycxftx.html