Open KrisGuoQin opened 4 years ago
import React from 'react'
import styled from 'styled-components'
const padding = '3em'
const Section = styled.section color: white; padding: ${padding}; background: ${props => props.background};
render(
)
在高阶组件中需要转发Refs特别有用。因为ref不会向下传递,在经过高阶组件包装后,ref并不是指向我们的组件,而是指向包装组件,可以使用forwardRef转发ref到我们的组件
const FancyButton = React.createRef((props, ref) => (
<button ref={ref}>
{props.children}
</button>
))
const ref = React.createRef()
<FancyButton ref={ref}>click me</FancyButton>
其中ref指向button元素,而不是FancyButton的实例
// 高阶组件
function logProps(Component) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
}
render() {
const {forwardedRef, ...rest} = this.props;
// 将自定义的 prop 属性 “forwardedRef” 定义为 ref
return <Component ref={forwardedRef} {...rest} />;
}
}
// 注意 React.forwardRef 回调的第二个参数 “ref”。
// 我们可以将其作为常规 prop 属性传递给 LogProps,例如 “forwardedRef”
// 然后它就可以被挂载到被 LogProps 包裹的子组件上。
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
});
}
function FancyButton (props, ref) {
const inputRef = useRef()
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus()
}
}))
return <input ref={inputRef} />
}
FancyButton = forwardRef(FancyButton)
FancyButton.focus()
const FancyButton = React.lazy(() => import('./FancyButton'))
function MyComponent () { return ( <Suspense fallback={
</Suspense>
)
}
项目地址React 16.8打造精美音乐WebApp