一个字符反应后文本输入不集中?

dor*_*cam 2 javascript reactjs

var uuid = require('uuid-v4');
// Generate a new UUID
var myUUID = uuid();
// Validate a UUID as proper V4 format
uuid.isUUID(myUUID);  // true

var questionNum = 0;

class App extends Component {

  constructor(props){
    super(props);
      this.state = {
        key: uuid(),
        title: "",
        author: "",
        questions: [],
        answers: []
      }

      this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    const target = event.target;
    const value = target.type === "checkbox" ? target.checked : target.value;
    const name = target.name;

    this.setState({
        [name]: value
    });
  }

  addQuestion = () => {
    questionNum++;
    this.setState({
      questions: this.state.questions.concat(["question","hi"])
    });
    console.log(this.state.questions);
    this.setState({
      answers: this.state.answers.concat(["hello","hi"])
    });
    console.log(this.state.answers);
    console.log(questionNum);
    console.log(this.state.title);
    console.log(this.state.author);
  }

  render() {
    return (
      <div className="App">

        <div>
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h1 className="App-title">Quiz Form 2.0</h1>
          </header>
          <p className="App-intro">
            To get started, edit <code>src/App.js</code> and save to reload.
          </p>
          </div>

        <div>
          <form>
            <div className="Intro">
              Give your Quiz a title: <input type="text" value={this.state.title} onChange={this.handleChange} name="title" key={uuid()}/><br/>
              Who's the Author? <input type="text" value={this.state.author} onChange={this.handleChange} name="author" key={uuid()}/><br/><br/>
            </div>
            <div className="questions">
              Now let's add some questions... <br/>
              {this.addQuestion}
            </div>
          </form>
          <button onClick={this.addQuestion}>Add Question</button>
        </div>

      </div>
    );
  }
}

export default App;
Run Code Online (Sandbox Code Playgroud)

只输入一个字符后,我页面上的两个输入都没有焦点。这是我的代码,我不完全确定我哪里出错了,昨天一切正常。

如果您还有什么需要了解的,请发表评论,我会处理的。非常感谢您的帮助,谢谢!

Tho*_*lle 7

key给一个组件的给定改变时,前一个被丢弃并安装一个新的组件。您正在为uuid()每次渲染创建一个新键,因此每次渲染都会创建一个新的输入组件。

key从您的输入中删除,它将按预期工作。

<div className="Intro">
  Give your Quiz a title:
  <input
    type="text"
    value={this.state.title}
    onChange={this.handleChange}
    name="title"
  />
  <br/>
  Who's the Author?
  <input
    type="text"
    value={this.state.author}
    onChange={this.handleChange}
    name="author"
  />
  <br/><br/>
</div>
Run Code Online (Sandbox Code Playgroud)