简体   繁体   中英

React+Typescript: How to add numeric fields and display output in the console?

I'm currently using a modal with 2 fields: one text and one numeric, but I'm unsure about how to set the name attribute of the numeric one and have it display in the console? The text one is working fine and can be displayed. Any help is appreciated. Here is the code:

interface State {
  contactName: string;
  amount: number;
}

interface Props {
  isOpen: boolean;
  handleClose: () => void;
  handleSendRequest: (values: State) => void;
}

export default class FormDialog extends React.Component<Props, State> {
  state = { contactName: "John", amount: 0 };//put 0 here for now since I get error if I put "number"

  onChange = (st: any) => (event: any) => {
    const newObject = { [st]: event.target.value } as Pick<State, keyof State>;
    this.setState(newObject);
    console.log(this.state);
  };

  render() {
    const { isOpen, handleClose, handleSendRequest } = this.props;
    return (
      <Dialog
        open={isOpen}
        onClose={handleClose}
        aria-labelledby="form-dialog-title"
      >
        <DialogTitle id="form-dialog-title">Send Money Request</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            id="standard-read-only-input"
            name="contactName"
            label="Contact Name"
            defaultValue={this.state.contactName}
            onChange={this.onChange("contactName")}
          />
          <TextField
            autoFocus
            margin="dense"
            id="amt"
            name="amount"   //need to make it so that the number appears in the console
            label="Amount"
            fullWidth
            onChange={this.onChange("amount")}
          />

The problem is not with the field per se I think, it has to do with when you call the ‛console.log‛. ‛setState‛ does not work immediately - it adds the new state to a queue and performs a component update later. If you want to see the new state value move it to the ‛render‛ method instead.

The second step is to use the value as either ‛defaultValue‛ or ‛value‛ in your ‛TextField‛ component (now you are only doing it for the ‛contactName‛

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM