栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

React实现双向绑定示例代码

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

React实现双向绑定示例代码

前言

React.js现在已经很流行了,不会React.js都不好意思说自己会前端了。

那么下面就来看看关于React双向绑定的实现。

双向绑定的使用:

组件需要mixins:引用linkedStateMixin。它提供一个linkState方法。

参数是state属性

双向绑定用valuelink={this.linkState(XX)}

linkState方法返回一个对象,有一个value属性,指定state的属性。

还有一个requestChange回调方法,用来实现state的修改。参数是新值

可以理解成onchange的绑定方法。可以自己写一个linkState对象,value是state.XX requestChange里用setState()来修改值。用valuelink={obj}来实现。

可以理解成this.linkState()实现的就是指定绑定值value 和change方法

valuelink属性实现了linkstate.value绑定到value requestChange方法绑定onChange

可以创建一个this.linkState('XX') value={XX.value} onchange={fn}方法内使用Xx.requestChange(e.target.value)

-------------------------

小结:linkState()方法提供state属性和change方法。valuelink={}来实现value 和change事件的绑定。

以下是实现代码


   var Box1=React.createClass({
   getInitialState:function(){
    return {
    name:'star',bool:true
    }
   },
   handlNameChange:function(event){
    this.setState({name:event.target.value});
   },handlboolChange:function(event){
    this.setState({bool:event.target.checked})
   },
   render:function(){
    return (
    
        
) } }) ; React.render(,document.querySelector('#div1')); var Box2=React.createClass({ mixins:[React.addons.linkedStateMixin],//添加引用 getInitialState:function(){ return { name:'star',bool:true } }, render:function(){//绑定时属性从value换成valuelink值需要用this.linkState方法调用 return (
); } }) React.render(,document.querySelector('#div2')); var Box3=React.createClass({ getInitialState:function(){ return { name:'star',bool:true } }, handlnamechange:function(val){ this.setState({name:val}) }, handlboolchange:function(val){ this.setState({bool:val}) }, render:function(){ var reactlink={ value:this.state.name, requestChange:this.handlnamechange } var reactlink2={ value:this.state.bool, requestChange:this.handlboolchange } return(
) } }); React.render(,document.querySelector('#div3')); var Box4=React.createClass({ mixins:[React.addons.linkedStateMixin],//添加引用 getInitialState:function(){ return { name:'star',bool:true } }, render:function(){ var valuelink=this.linkState('name'); var handlenamechange=function(e){ valuelink.requestChange(e.target.value) } var valuelink2=this.linkState('bool'); var handlenboolchange=function(e){ valuelink2.requestChange(e.target.checked) } return (
) } }); React.render(,document.querySelector('#div4'));

------------------------Reactlink对象传递

可以向子组件传递:

linkname={this.linkState('name')}

子组件内可:

通过props来引用并绑定到valuelink上。

也可以用this.props.linkname.requestChange()来用方法修改值 。

它们的变化 会同步到父组件的。并更新标签的。

总结

以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作能有所帮助,如果有疑问大家可以留言交流。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/94088.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号