十一、高阶组件参数传递
高阶组件的参数并非只是一个组件,它还可以接收其他参数。
function withPersistentData(WrappedComponent,key) { return class extends Component { componentWillMount() { let data = localStorage.getItem(key); this.setState({ data }); } render() { //通过{...this.props}把传递给当前组件的属性继续传递给被包装的组件 return <WrappedComponent data={this.state.data} {...this.props} /> } } } //被包装的组件 class MyComponent extends Component { constructor(props) { super(props); } render() { return ( <div> data:{this.props.data} </div> ) } } const TodoData = withPersistentData(MyComponent,'data') const TodoName = withPersistentData(MyComponent,'name')
实际情况中,我们很少使用这种方式传递参数,而是采用更加灵活、更具通用性的函数形式:HOC(...params)(WrappedComponent)。
HOC(...params)的返回值是一个高阶组件,高阶组件需要的参数是先传递给HOC函数的。改写如下:
function withPersistentData = (key) => (WrappedComponent) => { return class extends Component { componentWillMount() { let data = localStorage.getItem(key); this.setState({ data }); } render() { //通过{...this.props}把传递给当前组件的属性继续传递给被包装的组件 return <WrappedComponent data={this.state.data} {...this.props} /> } } } //被包装的组件 class MyComponent extends Component { render() { return ( <div> data:{this.props.data} </div> ) } } const TodoData = withPersistentData('data')(MyComponent) const TodoName = withPersistentData('name')(MyComponent)
这种形式的高阶组件大量出现在第三方库中,例如react-redux中的connect函数:
connnect(mapStateToProps,mapDispatchToProps)(WrappedComponent)
connect的参数mapStateToProps、mapDispatchToProps是函数类型,说明高阶组件的参数也可以是函数类型。例如把组件ComponentA连接到Redux上的写法类似于:
connnect(mapStateToProps,mapDispatchToProps)(ComponentA)