簡體   English   中英

如果更新 function 作為道具傳入並在子組件中使用,是否可以更新初始 state

[英]Is it possible to update the inital state if the update function was passed in as props and its used in child component

 import React , {useState} from "react"
    import ChildComponent from "./ChildComponent"
    
    const App = () => {
      const [name , setName] = useState(asd);
        return (
         <ChildComponent name = {name} setName = {setName}/>
          )
    export default App;

    import React from "react"
    const ChildComponent = (props) => {
        const handleClick = (props) => {
         props.setName(null)
    }
      return(
        <button onClick = {() => handleClick(props)}> X </button>
   <p>{props.name}</p>
          )
    }
    export default ChildComponent;

I want to change the value of current state 'name' from asd to null or an empty string by passing the setName function as props to ChildComponent and then accessing that function as props.setName in the child component. 但它沒有更新當前的 state “名稱”。

您不需要將props作為handleClick的參數傳遞,它將替換子組件變量props 所以你可以這樣做

const handleClick = () => {
         props.setName(null)
    }

並稱之為

<button onClick = {() => handleClick()}> X </button>

或這樣稱呼它(來自@geoffrey)

<button onClick = {handleClick}> X </button>

嘗試這個:

const App = () => {
        const [name , setName] = useState('asd');
        return (
          <ChildComponent name = {name} setName = {setName}/>
         )
      }
export default App;
const ChildComponent = (props) => {
        const handleClick = (props) => {
          props.setName(null)
      }
        return(
          <>
            <button onClick = {() => handleClick(props)}> X </button>
            <p>{props.name}</p>
          </>
        )
      }

就像ihsan-fajar-ramadhan說的,你不需要在 handleClick function 中傳遞 props 參數。

另外,我建議傳播道具以更清楚地了解您的代碼在做什么,例如:

const ChildComponent = ({name, setName}) => {
  const handleClick = (props) => {
    setName(null)
  }

  return(
    <>
      <button onClick = {() => handleClick()}> X </button>
      <p>{name}</p>
    </>
  )
}

export default function App() {
  const [name , setName] = useState("asd");
  return (
    <ChildComponent name = {name} setName = {setName}/>
  );
}

子組件的初始 state 將取決於父組件中的這一行:

const [name , setName] = useState("asd");

暫無
暫無

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

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