[英]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 调用函数刷新到 MyPage.js
MyTable.js MyTable.js
const MyTable = (props) => {
//Some state
const refresh = () => {//Do Refresh}
return(<Table/>);
}
export default MyTable;
MyPage.js我的页面.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 MyTable.js
const MyTable = (props) => {
props.refresh(() => {
// DO Refresh
});
return(<Table/>);
}
export default MyTable;
MyPage.js我的页面.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} />
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.