簡體   English   中英

React 使用功能組件更改父組件的內部功能

[英]React Change inner function of parent component using functional component

我有兩個組件:一個父組件和一個子組件,如下所示:

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>&nbsp;
      <button onClick={decrementCount}>-</button>
      {newDivElem()}
    </>
  );
}

export default App; 

function InternalApp(){
     return(
        <App />
    );
}
export default InternalApp; 

如何覆蓋 InternalApp 組件內的 App 組件內部函數newDivElem()

請提出一些想法。

您可以將該函數提取到一個 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>&nbsp;
      <button onClick={decrementCount}>-</button>
      {newDivElem()}
    </>
  );
}

如果你想覆蓋它,傳遞另一個函數作為道具:

function InternalApp(){
   return(
      <App newDivElem={() => <div>Something Else</div>} />
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM