首页 > 解决方案 > 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?

标签: react-nativefunctioncomponents

解决方案


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 ;

推荐阅读