[英]How can we share a state variables between two React components on the same page?
我在 App.js 中有兩個組件。 主App
組件(包含一個基本表單)和一個自定義TextInput
組件。 我理解理想情況下,最好有單獨的文件。 但是,我會盡量保持簡短和簡單。
無論如何,我用const [success, setSuccess] = useState(false);
聲明了一個狀態變量const [success, setSuccess] = useState(false);
在第一個組件中,並希望在第二個組件中使用它。 我嘗試在兩個組件之外聲明變量以啟用共享,但這不起作用。 我該怎么做呢? 我的意思是通常,我只會導出和導入,但在這里,兩個組件都在同一頁面上。
要共享狀態,您需要在父組件(在您的情況下為 App)中聲明狀態並將其發送到子組件(TextInput)
例如
function App() {
const [success, setSuccess] = useState(false);
...
return (
<TextInput success={success} setSuccess={setSuccess} />
);
}
function TextInput({success, setSuccess}) {
// use success/setSuccess from props
}
您必須從父級(應用程序組件)傳遞道具,例如:
function App() {
const [success, setSuccess] = useState(false);
return (
<TextInput success={success} />
);
}
並在 TextInput 組件中訪問它
function TextInput(props) {
//Access it using props.success
}
在這種情況下,如果您為文本輸入提供了 pascal case 命名,例如function TextInput(){...}
,那么即使它在同一文件中定義,react 也會將其視為單獨的組件。 這就是為什么App
組件的狀態變量不在TextInput
的范圍內
您可以通過以下任一方法來緩解這種情況,
function textInput(){
// the state variable 'success' and 'setSuccess' will be normally accessible here
return(
<div>
<input type="text" />
<div>
)
}
//return for the 'App' component
return(
<>
{textInput()}
</>
)
將狀態作為props
傳遞給TextInput
組件
如果您遵循這種方法,那么您也可以將TextInput
組件放在一個單獨的文件中
//parent 'App' component
function App(){
const [success, setSuccess] = useState(false);
return(
<>
<TextInput success={success} setSuccess={setSuccess}></TextInput>
</>
)
}
function TextInput(props){
const {success, setSuccess} = props;
// In here you can refer success and setSuccess normally as you would even if this is in a separate file
}
不知道我是否理解錯了,但是......
//App.js
function App() {
const [success, setSuccess] = useState(false);
return (
<TextInput success={success} />
<FormComponent success={success} />
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.