簡體   English   中英

React 父組件道具無法在子組件中使用 forwardRef 道具訪問

[英]React parent component props can't access using forwardRef props in child component

我有這樣的子組件。

父 => 子

當我從父組件向我的子組件發送道具時。 該道具無法訪問子組件。

const Parent = () => {
    const [renderCount, setRenderCount] = useState(4);

    const renderCountHandler = () => {
        setRenderCount(renderCount + 1);
    };

    return (
        <div>
           <Child renderCountHandler={renderCountHandler}/>
        </div>
    );
};


const Child = forwardRef((props, ref) => {

    //Can't access props.renderCountHandler Only props.children
    <div>{props.}</div>
});

我是reactjs的新生。 所以我對它了解不多。 如果有人能幫我解決這個問題。 這對我的學習真的很有幫助。❤️

您可以將statemethod作為props父組件傳遞給子組件。

在此處閱讀更多組件和道具

例子:

 const { forwardRef, useState } = React; const Parent = () => { const [renderCount, setRenderCount] = useState(4); const renderCountHandler = () => { setRenderCount(renderCount + 1); }; return ( <div> <p>{renderCount}</p> <br /> <Child renderCountHandler={renderCountHandler} /> </div> ); }; const Child = forwardRef((props, ref) => { //Can't access props.renderCountHandler Only props.children return ( <div ref={ref}> <button onClick={props.renderCountHandler}>Click Me</button> </div> ); }); ReactDOM.render(<Parent />, document.getElementById("root"));
 <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <div id="root"></div>

在您的代碼中一切正常。 我得到了“renderCountHandler”道具。 查看沙箱

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM