高阶组件(Higher Order Component)
高阶组件(HOC)是React开发中的特有名词,一个函数返回一个React组件,指的就是一个React组包裹着另一个React组件。可以理解为一个生产React组件的工厂。 有两种类型的HOC:
Props Proxy一种最简单的Props Proxy实现 function ppHOC(WrappedComponent) { return class PP extends React.Component { render() { return <WrappedComponent {...this.props}/> } } } 这里的HOC是一个方法,接受一个 const ListHOCInstance = ppHOC(List) <ListHOCInstance name='instance' type='hoc' /> 这个例子中,我们将本应该传给 在pp中,我们可以对
操作props比如添加新的props给 const isLogin = false; function ppHOC(WrappedComponent) { return class PP extends React.Component { render() { const newProps = { isNew: true,login: isLogin } return <WrappedComponent {...this.props} {...newProps}/> } } }
通过refs访问到组件实例function refsHOC(WrappedComponent) { return class RefsHOC extends React.Component { proc(wrappedComponentInstance) { wrappedComponentInstance.method() } render() { const props = Object.assign({},this.props,{ref: this.proc.bind(this)}) return <WrappedComponent {...props}/> } } } Ref 的回调函数会在 不过这里有个问题,如果 提取state你可以通过传入 props 和回调函数把 state 提取出来, function ppHOC(WrappedComponent) { return class PP extends React.Component { constructor(props) { super(props) this.state = { name: '' } this.onNameChange = this.onNameChange.bind(this) } onNameChange(event) { this.setState({ name: event.target.value }) } render() { const newProps = { name: { value: this.state.name,onChange: this.onNameChange } } return <WrappedComponent {...this.props} {...newProps}/> } } } 使用的时候: class Test extends React.Component { render () { return ( <input name="name" {...this.props.name}/> ); } } export default ppHOC(Test); 这样的话,就可以实现将input转化成受控组件。 用其他元素包裹 WrappedComponent这个比较好理解,就是将WrappedComponent组件外面包一层需要的嵌套结构 function ppHOC(WrappedComponent) { return class PP extends React.Component { render() { return ( <div style={{display: 'block'}}> <WrappedComponent {...this.props}/> </div> ) } } } Inheritance Inversion(反向继承)先看一个反向继承(ii)的 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |