我有這樣的子組件。
父 => 子
當我從父組件向我的子組件發送道具時。該道具無法訪問子組件。
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的新生。所以我對它了解不多。如果有人能幫我解決這個問題。這對我的學習真的很有幫助。??
uj5u.com熱心網友回復:
在您的代碼中一切正常。我得到了“renderCountHandler”道具。查看沙箱
uj5u.com熱心網友回復:
您可以將state或method作為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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/353998.html
標籤:javascript 反应 反应还原 反应钩子
上一篇:根據回應在反應中顯示影像
