[英]Updating Input Value with Input Passed Into Child Component with React Hooks
我有一個加載組件,它會創建一個骨架,直到內容通過@trainline/react-skeletor
。 在這種情況下,我正在為表單創建框架。
首先,我為想要查看正在發生的事情的人提供了一個CodeSandbox ,並將所有組件用於更好地了解解決方案。
我也正在使用基於功能的組件,並希望保持這種狀態,除非無法通過基於功能的組件來實現,否則我不想使用基於類的組件來解決此問題。
我有一個組件ProfileForm
,目前包含h3
和一個form
形式如下
const form = (
<>
<FormControl key={"profileForm"} submit={profileFormSubmit} form={profileFormData} validation={profileFormValidation}>
<InputControl autoComplete="off" type="text" name="emailAddress" placeholder="Email address" label="Email Address">
<ErrorMsg map="required" msg="Email is required"></ErrorMsg>
</InputControl>
</FormControl>
</>
)
FormControl
組件返回一個<form>
元素
InputControl
組件返回一個<label>
和<input>
元素
ErrorMsg
組件返回<div>
將呈現如下。
<form class="Form " novalidate="">
<div class="InputControl">
<div>
<label for="emailAddress">Email Address</label>
<input type="text" placeholder="Email address" name="emailAddress" id="emailAddress" autocomplete="off" value=""></div>
<div class="InputControl--Errors">
</div>
</div>
</form>
我創建了一個虛擬的http請求,在其中更新了帶有標題和上面的表單的狀態對象。
const [content, setContent] = useState();
const ttl = 500;
/*simulate http request*/
useEffect(() => {
const timeout = setTimeout(() => {
setContent({ title: "My Personal Details", form });
}, ttl);
return () => {
clearTimeout(timeout);
};
}, []);
作為回報,我將content
狀態對象作為道具傳遞了下來(注釋掉的代碼可以工作,但不會創建項目中所需的框架加載元素
return (
<div className="ProfileForm">
<h2 style={{ color: "red" }}>Not working: Passing Form Down to Child</h2>
<ProfileFormContainer content={content} />
{/* <h2 style={{ color: 'green' }}>Working: Render Directly in return</h2>
{form}*/}
</div>
);
ProfileFormContainer
創建骨架元素,然后將道具向下傳遞到另一個Component中,並在下面的代碼片段中返回。
const Wrapper = createSkeletonElement('div', 'Loader Loader--InlineBlock ProfileForm--loading');
const H3 = createSkeletonElement('h3', 'Loader Loader--InlineBlock');
const DIV = createSkeletonElement('div', 'Loader Loader--Block ');
const ProfileFormLoader = (props) => {
return (
<Wrapper className="ProfileForm">
<H3 className="ProfileForm-title">{ props.title }</H3>
<DIV>
{props.form}
</DIV>
</Wrapper>
);
}
export default ProfileFormLoader;
但是,這將按預期方式呈現,但是當我嘗試輸入輸入時,它不會更新輸入的值。 我的問題是,當像我一樣將輸入向下傳遞給子組件的道具時,如何在輸入上更新輸入的值?
任何幫助將不勝感激
這是發生的情況:您基本上只顯示useState
content
您模擬您的httpRequest,這會將content
更新為空格式
然后您再也不會更新content
,它仍然是第一個渲染的空白表格。
當您將form
保留在content
時,它會起作用,因為在每次渲染時都會使用實際profileFormData
評估form
。
我建議不要在您的情況下(可能還有其他大多數情況下)使用狀態存儲節點。 您的http請求的返回應填充一個您的模板可以讀取的數據存儲,但是鑒於您的表單也需要從其他來源讀取,例如當前的輸入狀態,因此將form
保存在渲染中更為安全,它將在每次渲染時更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.