简体   繁体   English

React+Typescript:如何添加数字字段并在控制台中显示 output?

[英]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?我目前正在使用具有 2 个字段的模式:一个文本和一个数字,但我不确定如何设置数字的名称属性并将其显示在控制台中? 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‛.我认为问题不在于字段本身,而与您调用‛console.log‛的时间有关。 ‛setState‛ does not work immediately - it adds the new state to a queue and performs a component update later. ‛setState‛ 不会立即起作用 - 它会将新的 state 添加到队列中并稍后执行组件更新。 If you want to see the new state value move it to the ‛render‛ method instead.如果您想查看新的 state 值,请将其移至 ‛render‛ 方法。

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‛第二步是在你的 ‛TextField‛ 组件中使用值作为 ‛defaultValue‛ 或 ‛value‛(现在你只为 ‛contactName‛

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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