[英]React Change inner function of parent component using functional component
I have two components: one parent and one in child component as shown below:我有两个组件:一个父组件和一个子组件,如下所示:
import React, { Component, useState, useEffect } from 'react';
const useDocumentTitle = (title) => {
useEffect(() => {
document.title = title;
}, [title])
}
function App(){
const [count,setCount] = useState(0);
const incrementCount = () => setCount(count + 1);
const decrementCount = () => setCount(count - 1);
const newDivElem = () => { return ( <>Hello World </>)}
useDocumentTitle(`You clicked ${count} times`);
return (
<>
Count of this value {count}
<br />
<button onClick={incrementCount}>+</button>
<button onClick={decrementCount}>-</button>
{newDivElem()}
</>
);
}
export default App;
function InternalApp(){
return(
<App />
);
}
export default InternalApp;
How can I overwrite the App component inner function newDivElem()
inside the InternalApp component?如何覆盖 InternalApp 组件内的 App 组件内部函数
newDivElem()
?
Please suggest some idea.请提出一些想法。
You can extract the function to a prop, and set the original function as the default value:您可以将该函数提取到一个 prop,并将原始函数设置为默认值:
const newDivElem = () => { return ( <>Hello World </>)}
function App({ newDivElem = newDivElem }){
const [count,setCount] = useState(0);
const incrementCount = () => setCount(count + 1);
const decrementCount = () => setCount(count - 1);
useDocumentTitle(`You clicked ${count} times`);
return (
<>
Count of this value {count}
<br />
<button onClick={incrementCount}>+</button>
<button onClick={decrementCount}>-</button>
{newDivElem()}
</>
);
}
If you want to override it, pass another function as the prop:如果你想覆盖它,传递另一个函数作为道具:
function InternalApp(){
return(
<App newDivElem={() => <div>Something Else</div>} />
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.