[英]Passing props from child function to parent function with React Native
Within Session() I want to access stateABC, which is in Item5().在 Session() 中,我想访问 stateABC,它在 Item5() 中。
The setup of my code looks like this:我的代码设置如下所示:
Session.js:会话.js:
function Session() {
//get handleRender(item).props.stateABC here
return (
<View>
{handleRender(item)}
</View>
);
}
handleRender.js: handleRender.js:
export function handleRender(item) {
if(item == "Item5"){
return (
{Item5()}
);
}
}
Item5.js:项目5.js:
export function Item5() {
const [stateABC, setStateABC] = useState("123");
return (
....
);
}
I tried to get the value in Session() by using handleRender(item).props.stateABC, but all I get is an empty value.我试图通过使用 handleRender(item).props.stateABC 来获取 Session() 中的值,但我得到的只是一个空值。
Is it possible to receive properties from a function like that or are props only accessible in class components?是否可以从这样的函数接收属性,或者道具只能在类组件中访问?
Any help is appreciated.任何帮助表示赞赏。
Thanks谢谢
If you need to access to stateABC
value from Session
component you have to pass a callback prop down from Session
to Item5
and call it every time you update stateABC
with setStateABC
, passing the new value to the callback.如果您需要从
Session
组件访问stateABC
值,您必须将回调道具从Session
传递到Item5
并在每次使用setStateABC
更新stateABC
时调用它,将新值传递给回调。
This is the simplest approach, you could also use React Context API
or even something like Redux
if you think that your app will grow in complexity.这是最简单的方法,如果你认为你的应用程序会变得越来越复杂,你也可以使用
React Context API
甚至类似Redux
东西。
Also, the approach that you tried to use is a bad idea.此外,您尝试使用的方法是一个坏主意。 It works only in class component but in any case you should not use it, it's a bad thing to access props directly.
它只适用于类组件,但无论如何你都不应该使用它,直接访问 props 是一件坏事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.