Home > OS >  How to call a component class function in my App.tsx?
How to call a component class function in my App.tsx?

Time:11-10

I am new in React Native and i'm trying to develop a mobile app with Expo.

I am trying to call a function of a component class in my App.tsx. I don't want that function is static because i need to access to my variable of my state which is in my constructor of my class.

App.tsx

const App = () => {

  const [variable, setVariable] = useState('');

  useEffect(() => {
      //doing some stuff 
  }, [])
  
  Class1.method(variable);
  
  [...]
}

Class1.tsx

class Class1 extends Component<any, any> {
  
  constructor(props: any){
    super(props);

    this.state = {
      company_name: [],
    }
  }

  method(param: any) {
    Object.values(param).map(function(d: any, idx){
      this.state.company_name = [...this.state.company_name, d];
    });
  }

  [...]

So the thing is that i am having an array in my App.tsx and i want to pass it to my Class1.

Is that possible to do in that way or am i missing something ?

Thanks in advance

CodePudding user response:

You should export your Class1 component by adding export default Class1; at the bottom of your Class1.tsx, after class declaration.

Then you will be able to import the component and use it in the App.tsx file.

Read this React doc on Code splitting to learn more.

CodePudding user response:

Put your array in props

const App = () => {
  const [names, setNames] = useState([]);

  const addCompanyName = (name) => {
    setNames([...names, name]);
  }

  const addRandomCompany = () => {
    addCompanyName(Math.random().toString());
  }

  return <>
    <Button title='random name' onPress={addRandomCompany}/>
    <Child companyNames={names}/>
  </>
}

const Child = ({ companyNames }) => {
  return <>
    {companyNames.map((name) => <Text>{name}</Text>)}
  </>
}
  • Related