我有两个组件:一个父组件和一个子组件,如下所示:
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;
如何覆盖InternalApp组件内部的App组件内部函数newDivElem()
?
请提出一些想法。
答案 0 :(得分:1)
您可以将函数提取为道具,并将原始函数设置为默认值:
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()}
</>
);
}
如果要覆盖它,请传递另一个函数作为prop:
function InternalApp(){
return(
<App newDivElem={() => <div>Something Else</div>} />
);
}