键入时输入内容无法填充

时间:2019-07-15 14:39:00

标签: reactjs react-redux

在输入标记中放置了value属性时,它没有从键盘输入而未显示输入

import React from 'react'

class Postform extends React.Component {
  state = {
    name: 'helo',
    email: '',
    password: '',
    bio: '',
  };

  changeHandler = (event) => {};

  submitHandler = (event) => {
    event.preventDefault();
  };

  render() {
    return (
      <div className="container">
        <form onSubmit={this.submitHandler}>
          <div classNam=" form-group ">
            <label htmlFor="name">Enter your name </label>
            <input
              placeholder="Enter your name"
              id="name"
              className="form-control"
              name="name"
              onChange={this.changeHandler}
              value="hello"
            />
          </div>
          <button type="submit" className="btn btn-info">
            submit
          </button>
        </form>
      </div>
    );
  }
}

export default Postform;

1 个答案:

答案 0 :(得分:0)

您将输入value设置为hello,这意味着无论如何它将保持hello

要使输入value动态,您需要将组件state中的值设置为输入value

这意味着当输入state使用value更改时,您还必须更新changeHandler

让我们从输入开始

// Always read the input value from state
// and when the input value changes call this.changeHandler
<input onChange={this.changeHandler} value={this.state.name} />

然后changeHandler

changeHandler = (event) => {
  // The input value has been changed, get the value from
  // event.target.value and set it as state.
  this.setState({ name: event.target.value });
};

现在state将被更新,组件将以当前re-render作为值state.name的输入