访问作为道具传递的组件的引用?

Accessing The Ref of a Component Passed Down as Props?

我正在传递样式组件

const Text = styled.span`
   font-size: 10px
`

render(){
   <Test comp = {<Text innerRef={(ref)=>{this.ref=ref}}>Hello</Text>}/>
}

Test 组件内部,我想访问 Textref,但我无法这样做。这可能吗?我想访问 Test 内的字体大小值。提前感谢所有帮助。

由于您将一个组件作为 prop 传递给另一个组件,React 根本不会渲染它,因此您没有 ref.

如果您的目标是将 Text 包装在 Test 中,正确的方法是将其作为 child 传递。这样 React 将实际渲染组件,并将生成其 ref.

const Text = styled.span`
   font-size: 10px
`

render(){
   <Test>
     <Text innerRef={ref => this.ref = ref}>Hello</Text>
   </Test>
}

如果您想访问 Test 中的 ref,您可以通过 this.props.children.ref

进行

编辑

由于 styled-components 有自己的道具来获得 ref,您需要使用 React.createRef() 并通过道具访问 ref

const Text = styled.span`
   font-size: 10px
`

class Test extends React.PureComponent {
  componentDidMount() {
    // This is how you access the ref ;)
    console.log(this.props.children.props.innerRef.current);
  }

  render() {
    return (
      <div className='test'>{this.props.children}</div>
    );
  }
}

class App extends React.PureComponent {

  render() {
    return (
      <Test>
        <Text innerRef={React.createRef()}/>
      </Test>
    );
  }
}