九、高阶组件基本概念

高阶函数是以函数为参数,并且返回值也是函数的函数。

高阶组件接收React组件作为参数,并且返回一个新的React组件高阶组件本质上也是一个函数,并不是一个组件

高阶组件的函数形式如下:

const EnhancedComponent = higherOrderComponent(WrappedComponent)

示例:

import Todo from "./components/Todo";
function App(props) {
  const tasks = [
    { id: "todo-0", name: "Eat", completed: true },
    { id: "todo-1", name: "Sleep", completed: false },
    { id: "todo-2", name: "Repeat", completed: false }
  ];
  const taskList = tasks.map(task => (
    <Todo name={task.name} key={task.id} />
  ));
  return (
      <ul
        role="list"
        className="todo-list stack-large stack-exception"
        aria-labelledby="list-heading"
      >
        {taskList}
      </ul>
  );
}
export default App;

Todo.js:

//高阶组件
function withPersistentData(WrappedComponent) {
    return class extends Component {
        componentWillMount() {
            // let data = localStorage.getItem('data');
            this.setState({data: 11});
        }
        render () {
            //this.props是WrappedComponent的props,data也将是WrappedComponent的props
            return <WrappedComponent data={this.state.data} {...this.props} />
        }
    }
}
//被包装的组件
class MyComponent extends Component {
    render() {
        return (
            <div>
                name:{this.props.name}<br/>
                data:{this.props.data}
            </div>
        )
    }
}
const Todo = withPersistentData(MyComponent)
export default Todo;

输出页面:

 

 

 

withPersistentData是一个高阶组件,返回一个新的组件,在新组件的componentWillMount中统一处理data,然后将获取到的数据通过props传递给被包装的组件WrappedComponent,这样WrappedComponent中可以直接使用this.props.data获取数据。

高阶组件的主要功能是封装并分离组件的通用逻辑,让通用逻辑在组件间更好的被复用。高阶组件的这种实现方式本质上是装饰者设计模式

posted on 2022-10-27 16:14  Zoie_ting  阅读(20)  评论(0编辑  收藏  举报