简体   繁体   中英

How can I call a function inside of stateless functional component in reactjs

Here is my problem I want to call function refresh from MyTable.js into MyPage.js

MyTable.js

const MyTable = (props) => {

 //Some state

 const refresh = () => {//Do Refresh}
 
 return(<Table/>);
}

export default MyTable;

MyPage.js

const MyPage = (props) => {
 //Some state

 const handleRefresh = () => {
  //How to call refresh of MyTable here?
 }

 return(
  <Button onClick={handleRefresh} >Refresh</Button>
  <MyTable />
 )
}

//I Want a solution something like this but I don't know how to achieve

const MyPage = (props) => {
 //Some state
const [myTable] = MyTable.useMyTable();

 const handleRefresh = () => {
  myTable.refresh();
 }

 return(
  <Button onClick={handleRefresh} >Refresh</Button>
  <MyTable table={myTable} />
 )
}

There is a way to do it but not highly recommended.

You can do it like the following

MyTable.js

const MyTable = (props) => {

 props.refresh(() => {
    // DO Refresh
 });

 return(<Table/>);
}

export default MyTable;

MyPage.js

const MyPage = (props) => {
 //Some state

 let refreshFunc = () => {};

 const handleRefresh = () => {
  //How to call refresh of MyTable here?
  refreshFunc();
 }

 return(
  <Button onClick={handleRefresh} >Refresh</Button>
  <MyTable refresh={r => { refreshFunc = r; }} />
 )
}

Try to patch as follows:

const MyPage = (props) => {
 //Some state
 const [refresh, setRefresh] = useState(0);

 const handleRefresh = () => {
  setRefresh(x => x + 1);
 }

 return(
  <Button onClick={handleRefresh} >Refresh</Button>
  <MyTable dummy={refresh} />
 )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM