我有一个根组件:
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)
最佳答案
因此,如果您想通过<FilledButton />
更新道具接收,则只需在触发action
onChange函数时存储一个状态(也许称为inputAction
),这样您便可以更新该状态,并且状态已传递给您的子组件:
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 />
并将其用作<input />
值,希望这对您有所帮助。关于javascript - 如何更新在JSX.Element内部创建的组件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57473523/