如何获得用户输入值并在React中显示基于该值的另一个元素



我正在尝试显示一个复选框("我同意"(,例如,如果用户年龄小于18岁,则不显示该复选框。

我写了一个handleAgreementCheckbox,如果用户小于18岁,它应该返回一个布尔值(truefalse(,不知道如何获取元素值并显示复选框。

我如何在React中做到这一点?

代码

import React from 'react'
import {
Form,
Field
} from 'react-advanced-form'
import {
Input,
Button
} from 'react-advanced-form-addons'
export default class RegistrationForm extends React.Component {
registerUser = ({
serialized,
fields,
form
}) => {
return fetch('https://backend.dev', {
body: JSON.stringify(serialized)
})
}
handleAgreementCheckbox = () => {
const currentTime = new Date();
const eligibleUserDOB = new Date(currentTime.getFullYear() - 18, currentTime.getMonth(), currentTime.getDate());
return currentTime>= eligibleUserDOB;
};
render() {
return (
<section className = "container">
<Form action = {
this.registerUser
}
onSubmitStart = {
this.props.onSubmitStart
}>
<Input name = "firstName"
label = "First name"
required = {
({
get
}) => {
return !!get(['lastName', 'value'])
}
}/>
<Input name = "lastName"
label = "Last name"
required = {
({
get
}) => {
return !!get(['firstName', 'value'])
}
}
/>
<Input name = "emailAddress"
type = "email"
label = "Email Address"
required />
<Input name = "phoneNumber"
type = "text"
label = "Phone Number"
required />
<Input name = "dateOfBirth"
type = "date"
label = "Date of Birth"
required />
<Input name = "eligibleAge"
type = "checkbox"
label = "I agree"
value = "unchecked"
/>
<Button primary> Submit </Button>
</Form>
</section>
);
}
}

(谢谢!我是React的新手。(

codesandbox上的演示

好的,首先创建一个状态来保持资格的true和false条件。然后在handleAgreementCheckbox方法中设置该状态。最后,使用资格状态根据true或false有条件地呈现复选框。

/**
* Registration form.
* The component we have built together as the part of
* React Advanced Form presentation on Medium.
*/
import React, { useState } from "react";
import { Form, Field } from "react-advanced-form";
import { Input, Button } from "react-advanced-form-addons";
// import 'react-phone-number-input/style.css'
// import PhoneInput from 'react-phone-number-input'
import PhoneInput from "react-phone-input-2";
import "react-phone-input-2/lib/style.css";
export default class RegistrationForm extends React.Component {
registerUser = ({ serialized, fields, form }) => {
return fetch("https://backend.dev", {
body: JSON.stringify(serialized)
});
};
state = { phone: "", eligible: false };
handleOnChange = value => {
console.log(value);
this.setState({ phone: value }, () => {
console.log(this.state.phone);
});
};
handleAgreementCheckbox = event => {
let selectedDate = event.nextValue; //======> fetch selected date and split it to pass into date object.
selectedDate = selectedDate.split("-");
console.log(selectedDate);
const currentTime = new Date();
const eligibleUserDOB = new Date(
selectedDate[0],
selectedDate[1] - 1,
selectedDate[2]
);
console.log(currentTime, eligibleUserDOB);
console.log(currentTime > eligibleUserDOB);
if (currentTime >= eligibleUserDOB) { //====> on greater set eligible to true
this.setState({ eligible: true });
} else {                              //====> on less set eligible to false
console.log(this.state);
this.setState({ eligible: false });
}
return currentTime >= eligibleUserDOB;
};
render() {
return (
<section className="container">
<Form
action={this.registerUser}
onSubmitStart={this.props.onSubmitStart}
>
<Input
name="firstName"
label="First name"
required={({ get }) => {
return !!get(["lastName", "value"]);
}}
/>
<Input
name="lastName"
label="Last name"
required={({ get }) => {
return !!get(["firstName", "value"]);
}}
/>
<Input
name="emailAddress"
type="email"
label="Email Address"
required
/>
<PhoneInput
name="phoneNumber"
type="text"
country={"us"}
enableAreaCodes={true}
onlyCountries={["us"]}
areaCodes={{ us: ["332"] }}
inputProps={{
name: "phone",
country: "us",
required: true,
autoFocus: true
}}
value={this.state.phone}
onChange={this.handleOnChange}
required
/>
<Input
name="dateOfBirth"
type="date"
label="Date of Birth"
onChange={this.handleAgreementCheckbox}
required
/>
{this.state.eligible && ( //===========> print the state here and change time to see it in working. It will display the check on true and hide on false
<Input
name="eligibleAge"
type="checkbox"
label="I agree"
value="unchecked"
/>
)}
<Button primary> Submit </Button>
</Form>
</section>
);
}
}
// <PhoneInput
//  country="US"
//  value={this.phoneNumberValidation.value}
//  onChange={this.phoneNumberValidation.setValue} />

工作演示在这里

相关内容

  • 没有找到相关文章

最新更新