一、定义
高阶函数:函数接受函数作为输入,或者输出一个函数。
高阶组件:接受React组件作为输入,或是输出一个组件。即hocFactory:: W: React.Component => E: React.Component
高阶组件让代码更有复用性、逻辑性、抽象性。
二、实现高阶函数的三种方法。
1. 属性继承??(将Input组件的name,onChange方法提取到高阶组件中)
const Mycontainer = (WrappedComponent) => { class extends React.Component { constructor(props) { super(props); this.state = { name: ‘‘, } this.onNameChange = this.onNameChange.bind(this); } onNameChange(event) { this.state({ name: event.target.value, }) } render() { const newProps = { name:{ value: this.state.name, onChange: this.onNameChange, } }; return <WrappedComponent {...this.props} {...newProps}/>; } } } class MyComponent extends React.Component { // ... } export default Mycontainer(MyComponent);
2. 反向继承
??渲染劫持: 就是高阶组件可以控制组件渲染以及props,state等。
const MyContainer = WrappedComponent => class extends WrappedComponent { render() { if (this.props.loggedIn) { return super.render(); } else { return null; } } }
3. 组件参数
??调用高阶组件时需要传递一些参数
function HOCFactoryFactory(...params) { // 可以做一些改变params的事情 return function HOCFactory(WrappedComponent) { return class HOC extends Component { render() { return <WrappedComponent {...this.props} {...params}/> } } } } HOCFactoryFactory(params)(WrappedComponent);
三、使用高阶组件使组件分离,抽象逻辑。
class SelectInput extends React.Component { static displayName = ‘SelectInput‘; render() { const { selectedItem, isActive, onClickHeader, placeholder } = this.props; const { text } = selectedItem; return ( <div> <div onClick={onClickHeader}> <input type="text" disabled value={text} placeholder={placeholder}/> <Icon className={isActive} name="angle-name"/> </div> </div> ); } } const searchDecorator = WrappedComponent => { class SearchDecorator extends React.Component { constructor(props){ super(props); this.handleSearch = this.handleSearch.bind(this); } handleSearch(keyword) { this.setState({ data: this.props.data, keyword, }); this.props.onSearch(keyword); } render() { const { data, keyword } = this.state; return ( <WrappedComponent {...this.props} data={data} keyword={keyword} onSearch={this.handleSearch} /> ) } } return SearchDecorator; } const asyncSelectDecorator = WrappedComponent => { class AsyncSelectDecorator extends React.Component { componentDidMount() { const { url, params } = this.props; fetch(url, { params }).then(data => { this.setState({ data, }); }); } render() { return ( <WrappedComponent {...this.props} data={this.state.data} /> ) } } return AsyncSelectDecorator; } class App extends React.Component { render() { const Input = searchDecorator(asyncSelectDecorator(SelectInput)) return { <Input {...this.props} />
} } }
原文地址:https://www.cnblogs.com/fange/p/12368119.html
时间: 2024-11-06 07:38:42