V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
Yukee798

前辈请问一下 React 中有没有什么办法可以从子组件中获取父组件传来的 key、ref 这种 props

  •  
  •   Yukee798 · May 27, 2021 · 1828 views
    This topic created in 1807 days ago, the information mentioned may be changed or developed.
    
    const Div = (props: { key: any, ref: any }) => {
    
      useEffect(() => {
        // 打印为 undefined
        console.log(props.key);
        console.log(props.ref);
        
      }, [])
    
      return (
        <div></div>
      )
    }
    
    export default function App() {
      const ref = useRef();
    
      return (
        <Div
          key={1}
          ref={ref}
        />
      )
    }
    
    4 replies    2021-05-27 22:32:30 +08:00
    Yukee798
        1
    Yukee798  
    OP
       May 27, 2021
    应该是不可以这样做的 = =,不好意思。
    dekuofa
        2
    dekuofa  
       May 27, 2021   ❤️ 1
    key 不行,但是 ref 可以
    去看一下 React.forwardRef
    xiadd
        3
    xiadd  
       May 27, 2021
    通过 props 再传一下呗
    Yukee798
        4
    Yukee798  
    OP
       May 27, 2021
    @dekuofa 学习啦,十分感谢!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1114 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 18:24 · PVG 02:24 · LAX 11:24 · JFK 14:24
    ♥ Do have faith in what you're doing.