简体   繁体   English

React+typescript:如果我将 state 作为数组接收,如何更改它?

[英]React+typescript : How to change the state if I take it in as an array?

This is my code for a modal form I'm using and I wanted to use my function to console.log, but I'm not sure how to change the state in this.set.state?这是我正在使用的模态表单的代码,我想将我的 function 用于 console.log,但我不确定如何更改 this.set.Z9ED39E2EA9312EF577A985A649 中的 state Any help is appreciated since Im very new to react.任何帮助表示赞赏,因为我很新反应。 The variable st is just the string it takes in each time变量 st 就是它每次传入的字符串

interface State {
  name: string;
  email: string;
  amt: string;
}

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

    export default class FormDialog extends React.Component<Props, State> {
      state = { name: "", email: "", amt: "" };

      onChange = ((st: string) => (event: any) => {
        const newObject: any = {};
        newObject[st] = event.target.value;
        this.setState({ State: newObject[st] }); //this part im struggling with
      }).bind(this);

      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="name"
                label="Contact Name"
                defaultValue="John"
                onChange={this.onChange("name")}
              />

Here is a simple example in javascript, which will log the state after it has been changed.这是 javascript 中的一个简单示例,它将在 state 更改后记录它。

 class Hello extends React.Component { constructor(props) { super(props) this.state = { name: "" } this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ name: event.target.value }, () => console.log(this.state)); } render() { return <div > < input type = "text" id = "name" onChange = { this.handleChange } /></div >; } } ReactDOM.render( < Hello / >, document.getElementById('container') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="container"> <.-- This element's contents will be replaced with your component. --> </div>

CodeSandbox example 代码沙盒示例


You can cast newObject as seen below.您可以newObject ,如下所示。 This answer was derived from this Stack Overflow answer .这个答案来自这个Stack Overflow 答案

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



EDIT:编辑:

In response to: [H]ow it come it doesn't work for default values in the text field?回应: [H]它为什么不适用于文本字段中的默认值? If i take the default tag off and enter a new value it works tho如果我关闭默认标签并输入一个新值,它可以工作

This is because defaultValue for your input is hard coded.这是因为您输入的defaultValue是硬编码的。 Your component doesn't know about the value you defined in your input.您的组件不知道您在输入中定义的值。 You would have to move the default value into your state and provide the value to the <TextField /> component.您必须将默认值移动到 state 并将该值提供给<TextField />组件。


export default class FormDialog extends React.Component<Props, State> {
  state = {
    name: "John", // Define the default value here
    email: "",
    amt: "",
  };

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

  render() {
    return (
      <TextField
        defaultValue={this.state.name} // Pass the default value as a prop here
        onChange={this.onChange("name")}
      />
    );
  }
}

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

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