[英]How to update components created inside a JSX.Element?
我有一個根組件:
const EnterMobileNumberPage: React.FC = () => {
return (
<div
className="Page"
id="enterMobileNumberPage"
>
<CardView>
<p
className="TitleLabel"
>
Please enter your mobile number
</p>
<input
className="PlainInput"
type="text"
maxLength={10}
onChange={inputAction}
/>
<FilledButton
title="Next"
action={buttonAction}
invalid
/>
</CardView>
</div>
);
}
其中CardView
和FilledButton
是我的自定義組件。 FilledButton
邏輯如下所示:
type FilledButtonProps = {
title: string,
bgcolor?: string,
color?: string,
invalid?: boolean,
action?: ()=>void
}
const FilledButton: React.FC<FilledButtonProps> = (props) => {
const [, updateState] = React.useState();
const forceUpdate = React.useCallback(() => updateState({}), []);
let backgroundColor: string | undefined
if(props.bgcolor){
backgroundColor = props.bgcolor
}
if(props.invalid === true){
backgroundColor = "#bcbcbc"
}
const overrideStyle: CSS.Properties = {
backgroundColor: backgroundColor,
color: props.color
}
return (
<a
className="FilledButton"
onClick={props.action}
>
<div style={overrideStyle}>
{props.title}
</div>
</a>
);
}
在這里,我想聽輸入元素中的文本更改事件。 我應該怎么寫,以便inputAction
可以更新FilledButton
?
例如,當輸入元素具有10位數字時,我可能想將FilledButton
的invalid
更改為false
。
(因為我是個初學者,所以我沒有介紹Redux)
由於要更新同級組件,所以唯一的方法是重新渲染父級組件,並將更新的prop傳遞給同級組件,以便它也將更新。
const EnterMobileNumberPage: React.FC = () => {
const [mobileVal, inputAction] = React.useState('');
return (
<div>
<input
className="PlainInput"
type="text"
maxLength={10}
onChange={inputAction} // Updating parent component state on change
/>
<FilledButton
title="Next"
action={buttonAction}
invalid
mobileLength={mobileVal.length} // New prop for filled button
/>
</div>
);
}
因此,如果您想通過<FilledButton />
更新道具接收,則只需在inputAction
onChange函數被觸發時存儲一個狀態(可以將其稱為action
),那樣您就可以更新該狀態並且該狀態為傳遞給您的孩子組件:
import React, { useState } from 'react';
const EnterMobileNumberPage: React.FC = () => {
const [action, setAction] = React.useState('');
const handleChange = e => {
if (e && e.target && e.target.value) {
setAction(e.target.value);
}
};
return (
<div
className="Page"
id="enterMobileNumberPage"
>
<CardView>
<p className="TitleLabel" >
Please enter your mobile number
</p>
<input
className="PlainInput"
type="text"
maxLength={10}
onChange={handleChange}
/>
<FilledButton
title="Next"
action={buttonAction}
invalid={action.length === 10}
/>
</CardView>
</div>
);
}
然后,您將獲得一個action
<FilledButton />
,可用於阻止<FilledButton />
並將其用作<input />
值,希望這對您<FilledButton />
幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.