React中输入一个字符后文本框失去焦点的问题?

3
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;

我的页面上的两个输入框在输入一个字符后就失去了焦点。这是我的代码,我不确定哪里出了问题,昨天还一切正常。
如果您需要了解更多信息,请留下评论,我会尽快回复。非常感谢您的帮助!

所以,对于函数组件,必须有一个componentDidUpdate函数或useEffect函数在每次重新渲染时运行。 - Ahmedakhtar11
2个回答

9

当给组件传递的 key 改变时,之前的组件会被抛弃并且新的组件会被挂载。你每次渲染都使用 uuid() 创建一个新的 key,因此每次渲染都会创建一个新的输入组件。

从你的输入组件中移除 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>

2

Tholle的回答是正确的。但是,你需要对状态的交互方式进行一些调整。我已经通过注释重新制定了你的代码,并包括了uuid修复。

class App extends Component {
  constructor(props){
    super(props);
      this.state = {
        title: "",
        author: "",
        questions: [],
        answers: []
      }

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

  handleChange({ target }) {
    // since you'll always have a synthetic event just destructure the target
    const { checked, name, type, value } = target;
    const val = type === 'checkbox' ? checked : value;

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

  addQuestion() {
    // never modify state directly -> copy state and modify
    const { answers, questions } = Object.assign({}, this.state);
    // update your answers
    answers.push(["hello", "hi"]);
    // update your questions
    questions.push(["question", "hi"]);
    // now update state
    this.setState({
      answers,
      questions
    }, () => {
      console.log(this.state);        
    });
  }

  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" /><br/>
              Who's the Author? <input type="text" value={this.state.author} onChange={this.handleChange} name="author" /><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;

谢谢你的建议! - dorkycam
实际上,这里似乎有些问题。当我点击我的“添加问题”按钮时,会出现以下错误 TypeError: Cannot read property 'state' of undefined - dorkycam
我忘记将addQuestion绑定到正确的作用域。示例已更新。 - dysfunc
那么,如果我们移除了这个键,我们该如何解决唯一键警告? - Himanshu Teotia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接