React parent 组件道具无法使用 child 组件中的 forwardRef 道具访问
React parent component props can't access using forwardRef props in child component
我有 Child 个这样的组件。
Parent => Child
当我从 parent 组件向我的 child 组件发送道具时。该道具无法访问 child 个组件。
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的新生。所以我对它了解不多。如果有人可以帮助我。对我的学习帮助很大❤️
您可以将 state
或 method
作为 props
父组件传递给子组件。
在此处阅读更多内容 components-and-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”道具。见 sandbox
我有 Child 个这样的组件。
Parent => Child
当我从 parent 组件向我的 child 组件发送道具时。该道具无法访问 child 个组件。
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的新生。所以我对它了解不多。如果有人可以帮助我。对我的学习帮助很大❤️
您可以将 state
或 method
作为 props
父组件传递给子组件。
在此处阅读更多内容 components-and-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”道具。见 sandbox