背景
我们都知道,react框架数据流是单项的,不像Vue是双向数据流。先前学习高阶组件的时候,了解到hoc可以抽离组件的state,后面才意识到,可以通过这种方法实现双向数据流。最近在写官网的时候,有涉及到input框数据的处理,嗯,然后就尝试用双向数据流
实现步骤
- 将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无法输入值,至于原因嘛,就是原始对象存储的都是值,而对象存储的都是地址,在赋值的过程中,新对象得到的自然是存储这个值得地址。