现构思写一个通用组件,能完成多个业务场景的复用,如下
<Fu onScrollIn={(this)=>{this.setState({}}>
<Zi>
</Fu>
当滚动到Zi组件进入视野后,父组件触发onScrollIn函数这个函数(参数是子组件实例,可操作state对子组件内部状态实现控制).
现在思路是Zi组件由于可以是任意组件,没有固定要求,所以需要hoc套一层壳子来获取ref获取scrollTop,使用的react16新特性代码如下:
const withRef = (WrappedComponent) => {
class Hoc extends Component {
render() {
const {forwardedRef, ...rest} = this.props
return <WrappedComponent ref={forwardedRef} {...rest}/>
}
}
return React.forwardRef((props, ref) => {
return <Hoc {...props} forwardedRef={ref}/>
})
}
@withRef
class Child extends Component {
constructor(props) {
super()
this.state = {
test: 124
}
}
render() {
return (
<input defaultValue="123"/>
)
}
}
class InView extends Component {
constructor() {
super()
this.myRef = React.createRef()
}
componentDidMount() {
console.log(this.myRef.current)
}
render() {
return (
<Child ref={this.myRef}/>
)
}
}
InView是我的通用组件,Child是子组件(如代码所示Child可以是任意组件所以input中没有写ref,为了实现高复用),但现在日志打印出来current为Child,也就是子组件实例,请问有什么方法能获取到Child里包裹的input的ref进而可以获取内容的高度来完成我的需求?谢谢