我是 React 的新手。我們可以改變道具的狀態嗎?例如,我有 2 段代碼
應用程式.js
import React, { useState } from 'react'
import Print from '../components/Print/print'
const [text, setText] = useState("Hi");
<Print text = {text} />
列印.js
import React, { useState } from 'react'
const Print = (props) => {
return(
<p>props</p>
)
export default Print
有沒有辦法來改變道具,即使用狀態useState()的print.js更新狀態。例如,我們可以setText(prop)在print.js. 如果不是這樣,那么您將如何從print.jsfor 變數tech中觸發狀態更改App.js?
uj5u.com熱心網友回復:
您不能也不應該嘗試直接在子組件中更改道具的狀態或值。對于更改道具,您可以將函式作為道具傳遞,然后將新值發送給該函式。因此,該函式會將您的道具更改為父組件,并將進一步傳遞給其子組件。
<Print text = {text} changeText = {(newVal) => setText(newVal)}/>
并在您的子組件中changeText使用新值呼叫此函式。
return (
<>
<p>{props.text}</p>
<div onClick={props.changeText('Hello')}>Change Text</div>
</>
);
僅供參考,{props}是一個陣列,您可以通過以下方式訪問文本{props.text}
uj5u.com熱心網友回復:
你可以試試這個
- 通過 props 在 print.js 中傳遞 text 和 setText
- 然后使用 setText 更新組件的狀態
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/396976.html
標籤:javascript 反应 反应还原 反应钩子
