react-native - How to pass function between multiple components in React Native
问题描述
I have problem and I didnt find answer, so I try anyone who could help with:
I have main app component:
export default class App extends React.Component {
constructor(props) {...}
openSettings = () => { ....some changing state}
render(){
return (...
<Settings openSettings={() =>this.openSettings()}/>
);}
...};
My Settings file :
const Settings = ({openSetting}) => {
return (
<MyHeader openSetting={openSetting}></MyHeader>...
)}
export default Settings;
And I want to pass openSetting to another file:
const MyHeader = ({openSetting}) => {
return (
<Text onPress={openSetting}>Open it!</Text>
)}
export default MyHeader ;
Anyone knows why it doesnt work?
解决方案
Its probably the typo on your code thats causing this issue, and its not working.
You created a function named openSettings, but you sent the props as openSetting. Try writing the prop name correctly without typo and it should work.
export default class App extends React.Component {
constructor(props) {...}
openSettings = () => { ....some changing state}
render(){
return (...
<Settings openSettings={() =>this.openSettings()}/> //<== Check this line
);}
...};
const Settings = ({openSettings}) => { //<== Check this line
return (
<MyHeader openSettings={openSettings}></MyHeader>... //<== Check this line
)}
export default Settings;
const MyHeader = ({openSettings}) => { //<== Check this line
return (
<Text onPress={openSettings}>Open it!</Text> //<== Check this line
)}
export default MyHeader ;
推荐阅读
- java - 从十进制字符串中删除前导零
- typescript - vue-class-component : 调用类方法时 TS2339
- html - 我的密码验证没有正确执行
- vue.js - 通过组件从外部 api 加载路由并将它们添加到路由器
- c++ - 使用指针作为参数的调用函数内部的对象为空
- elasticsearch - 从嵌套查询中过滤记录 - 弹性搜索
- sql - 避免使用 sum 的笛卡尔积
- excel - 基于另一张表中的动态自动过滤器在一张表上创建图表 - 返回不正确的范围
- typescript - 如何找到我的应用程序中定义的 TS 类型?
- c# - c# 从 linq join 返回命名元组