hoc实现react双向数据

博客介绍了在React框架中利用高阶组件(HOC)实现双向数据流。因React是单向数据流,而学习HOC时发现可抽离组件state来实现双向。实现步骤为将state抽离到HOC中,在需要的组件中使用该HOC组件,还说明了使用时的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

背景

我们都知道,react框架数据流是单项的,不像Vue是双向数据流。先前学习高阶组件的时候,了解到hoc可以抽离组件的state,后面才意识到,可以通过这种方法实现双向数据流。最近在写官网的时候,有涉及到input框数据的处理,嗯,然后就尝试用双向数据流
实现步骤

  1. 将state抽离到hoc中
const twoWayDataHoc = (WrappedCom) => {
   return class TwoWayData extends Component{
       constructor () {
           super()
           this.state = {
               fields: {}
           }
       }
       getFields = (fieldsName) => {
           let newFiels = {...this.state.fields}
           if(!newFiels[fieldsName]){
               newFiels[fieldsName] = {
                   value: '',
                   onChange: (event) => {
                       newFiels[fieldsName].value = event.target.value;
                       this.setState({
                           fields: {...newFiels}
                       })
                   }
               }
               this.setState({
                   fields: {...newFiels}
               })
           }
           return newFiels[fieldsName]
       }
       render () {
           let props = Object.assign({},this.porps,{fields: this.getFields})
           return (
               <WrappedCom {...props}/>
           )
       }
   }
}
export default twoWayDataHoc

2.在需要的组件中使用该hoc组件

class Home extends Component{
   constructor () {
       super();
       this.username = {}
       this.password = {}
   }

   componentDidMount () {
       this.username = this.props.fields('username')
       this.password = this.props.fields('password')
   }

   render () {
       this.username.value="test"
       return (
           <div>
               <input type="text" {...this.username}/>
               <input type="text" {...this.password} />
               <p>{this.username.value}</p>
           </div>
       )
   }
}

export default twoWayDataHoc(Home)

说明:
若在hoc组件中 getFields中返回一个新对象:如下:

    return{
               value: newFiels[fieldsName].value,
               onChange: newFiels[fieldsName].value
           }

这种情况下,不能再Home组件的 componentDidMount中调用hoc的getFields 函数,不然input无法输入值,至于原因嘛,就是原始对象存储的都是值,而对象存储的都是地址,在赋值的过程中,新对象得到的自然是存储这个值得地址。

参考资料

react-hoc-examples/pp_state.js

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值