我正在使用react。我想保持一个按钮禁用,直到所有的文本区域被填充。一旦所有的文本区域都填满,按钮应该启用。我怎样才能做到这一点呢?如果我为每个输入添加验证,是否有可能?我在下面添加我的代码。谢谢你。
我的代码是:
App.tsx:
interface IState {
cName: string;
cEmail: string;
}
class App extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
cName: '',
cEmail: ''
}
this.nameChange = this.nameChange.bind(this);
this.emailChange = this.emailChange.bind(this);
this.computeBmi = this.computeBmi.bind(this);
}
nameChange(nameValue) {
this.setState({ cName : nameValue });
}
emailChange(emailValue) {
this.setState({ cEmail : emailValue });
}
computeBmi() {
// some code here
}
render() {
return (
<div>
<div class="step_one">
<TextInput label="Please confirm your full name?" placeholder="Full name" onChange={this.nameChange} />
<TextInput label="Please confirm your email?" placeholder="Email ID" onChange={this.emailChange} />
<MyButton label="SUBMIT" onClick={ this.computeBmi } />
</div>
<div class="step_two">
// some code
</div>
</div>
)
}
}
export default App;
TextInput.tsx
interface TIProps {
label?: any;
placeholder?: any;
onChange(inputValue: string): any;
}
interface TIState {
value: number;
error: string;
}
class TextInput extends React.Component<TIProps, TIState> {
constructor(props: TIProps) {
super(props);
this.state = {
value : 0,
error : ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
let inputValue = event.target.value;
this.setState({ value : inputValue });
this.props.onChange(inputValue);
}
render() {
return(
<div>
<FormControl>
<TextField label={ this.props.label } type="text" placeholder={this.props.placeholder} onChange={this.handleChange} />
</FormControl>
</div>
)
}
}
export default TextInput;
MyButton.tsx
interface BIProps {
label?: any;
variant?: any;
size?: any;
color?: any;
onClick: React.MouseEventHandler<HTMLButtonElement>;
}
interface BIState {
}
class MyButton extends React.Component<BIProps, BIState> {
render() {
return(
<button className="myButton" onClick={this.props.onClick}>
{this.props.label}
</button>
)
}
}
export default MyButton;
您可以在提交按钮中添加一个disabled
标记,并使用三元操作来检查nameValue
和emailValue
状态是否为空。像这样:
<MyButton disabled={nameValue && emailValue ? false : true} label="SUBMIT" onClick={ this.computeBmi } />