使用表单元素对错与正确的做法

问题描述 投票:0回答:1

Hyall

您能否在下面的代码中指出不良做法/错误?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "default title"
    };
    this.inputTxt = this.state.title;

    this.myRef = React.createRef();
  }

  componentDidMount() {
    this.myRef.current.value = this.inputTxt;
  }

  handleSubmit = e => {
    e.preventDefault();
    console.log("submitted");
    this.setState({ ...this.state, title: this.inputTxt });
  };

  handleInput = e => {
    this.inputTxt = e.target.value;
  };

  render() {
    return (
      <>
        <div>{this.state.title}</div>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            onChange={this.handleInput}
            ref={this.myRef}
          ></input>
          <button type="submit">Save</button>
          <button type="reset">Reset</button>
        </form>
      </>
    );
  }
}

以及一些特殊问题:

  1. 是否可以使用组件类的this.somevar属性存储变量的值?如何避免命名冲突?

  2. 使用引用来设置输入的值是否正常?

  3. 如果我想在一个输入控件中设置onChange和绑定到反应变量的值,它将冻结吗?如何获得对输入元素的[(ngModel)]角度控制?

reactjs forms state ref
1个回答
0
投票

似乎您已经使事情复杂化了。我认为这里不需要裁判。只需使用状态作为值,并在更改时更新状态。为了保持灵活性,请使用输入名称作为状态键。像这样的东西:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "default title"
    };
  }

  handleSubmit = e => {
    e.preventDefault();
    console.log("submitted");
    this.setState({ title: this.state.input1 }); // Not sure if thats what you're looking for
  };

  handleChange = e => {
    // use e.target.name as the computed property name, so it can be used for infinite number of inputs
    this.setState({[e.target.name]: e.target.value});
  };

  render() {
    return (
      <>
        <div>{this.state.title}</div>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            name="input1" // Give it a unique name for setting state
            value={this.state.input1} // Specify the value instead of using a ref
            onChange={this.handleChange}
          ></input>
          <button type="submit">Save</button>
          <button type="reset">Reset</button>
        </form>
      </>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.