高阶组件
HOC
- HOC 其实就是一个函数, 接收参数是一个组件,但返回值是一个组件
看一个简单的高阶组件
function visibleHOC(WrappedComponent) {
return class extends Component {
render() {
const { visible } = this.props;
if(!visible) return null;
return <WrappedComponent {...this.props}>
}
}
}
Render Props
const CustomModal = ({visible, cancel}) => {
return (
<Modal visible={visible} onCancel={cancel} >
Hello World
</Modal>
)
}
class ModalContainer extends Component {
state = {
visible: false
}
handleCancel = () => {
this.setState({
visible: false
})
}
show = () => {
this.setState({
visible: true
})
}
render() {
const { visible } = this.state;
const { children } = this.props;
return (
children({
visible: visible,
show: this.show,
cancel: this.handleCancel
})
)
}
}
class App extends Component {
render() {
return (
<div>
<ModalContainer>
({visible, show, cancel}) => (
<>
<CustomModal visible={visible} cancel={cancel}></CustomModal>
<Button type="primary" onClick={show}>
Click
</Button>
</>
)
</ModalContainer>
</div>
)
}
}