[英]List props of a nested react component
I want to enumerate children props of a nested component without passing them over.我想枚举嵌套组件的子道具而不传递它们。 Let's take a look at this example (pseudo code)
我们来看一下这个例子(伪代码)
# JSX
<Root>
<NodeWrapper />
</Root>
# NodeWrapper component
function NodeWrapper() {
return <InnerNode myPropName="myPropValue" />
}
# Root component
function Root({children}) {
// children.props > lists all NodeWrapper props
// how to get a hold of InnerNode props, so that Root can detect prop `myPropName`?
}
The only way I found so far is to pass myPropName
to NodeWrapper
.到目前为止,我发现的唯一方法是将
myPropName
传递给NodeWrapper
。 Is there a way to grab myPropName
value from within Root
component without passing it down from Root
to InnerNode
through NodeWrapper
?有没有办法从
Root
组件中获取myPropName
值,而无需通过NodeWrapper
将其从Root
传递到InnerNode
?
I understand InnerNode
will be available only when NodeWrapper
is rendered, that is not the case as Root
is being rendered and InnerNode
is not rendered yet (ie, it is a component and not yet an instance).我知道只有在渲染
InnerNode
时NodeWrapper
用,情况并非如此,因为Root
正在渲染并且InnerNode
尚未渲染(即,它是一个组件而不是一个实例)。
I think this question hides some React concept I am missing.我认为这个问题隐藏了我缺少的一些 React 概念。
EDIT: Please note that my question is not to avoid prop drilling.编辑:请注意,我的问题不是避免螺旋钻。 Prop drilling and contexts are techniques to pass data down the component tree.
道具钻取和上下文是将数据向下传递到组件树的技术。 What I want to do is quite the opposite: read a nested component props from the Root.
我想做的恰恰相反:从 Root 中读取一个嵌套的组件 props。 The usage of Root.children gives me only NodeWrapper props, but I do actually would like to get InnerNode props from within Root component.
Root.children 的使用只给了我 NodeWrapper 道具,但我确实想从 Root 组件中获取 InnerNode 道具。
I think you are trying to avoid props drilling that is passing props to children where it is not directly needed but it is needed inside some nested component.我认为您正在尝试避免将道具传递给不直接需要但在某些嵌套组件中需要的子项的道具钻孔。 For this I would recommend to use Context it is great way to avoid prop drilling here how you can configure it
为此,我建议使用上下文,这是避免道具钻孔的好方法,您可以如何配置它
import './App.css';
import { useContext } from 'react';
// In the login Component
const InnerComponent = () => {
const authContext = useContext(MyContext);
const handleLogin = () => {
authContext.onAuthChange(true); // this will make the user login that change the value of auth to true
}
return (
<div>Login JSX</div>
)
}
const MyContext = React.createContext(null);
const NodeWrapper = () => <InnerComponent />
function App() {
const [auth, setAuth] = React.useState(true);
const handleAuthChange = (newAuthState) => {
setAuth(newAuthState);
}
return (
<MyContext.Provider value={{
auth,
onAuthChange: handleAuthChange
}}>
<NodeWrapper />
</MyContext.Provider>
);
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.