I want to put some block of code in a function with 2 parameters and call it in the class component. the function should be present outside the class component. how I can implement it. I am new in react native please help me to implement this.
CodePudding user response:
You may want to consider using props to pass data from one component to another. In the example below, I use props to pass name
and time
from the App
class component to the Welcome
function component.
Take a look at https://reactjs.org/docs/components-and-props.html for more information.
import './App.css';
import React from "react";
function ComponentFunction(props) {
return (
<h1>Hello {props.name}, it is {props.time}</h1>
);
}
class App extends React.Component {
render() {
return (
<div className="App">
<ComponentFunction name="Josh" time={new Date().toLocaleTimeString()}/>
</div>
);
}
}
export default App;
CodePudding user response:
You can create your function in any other file and export it and then import in your needed component file.
For example:
in utils.js
export const myFunctionToExport = (param1, param2) => {
//DO YOUR STUFF
}
and in your other file you can import it :
import { myFunctionToExport } from './utils' // make sure the path is right
and use it wherever you'd like as such:
myFunctionToExport(param1, param2)
or assign it to a const if it returns something:
const myReturnedValue = myFunctionToExport(param1, param2)