【问题标题】:Text input unfocused after one character React?一个字符反应后文本输入没有焦点?
【发布时间】:2018-12-18 12:23:18
【问题描述】:
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;

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

如果您还有其他需要了解的内容,请发表评论,我会解答的。非常感谢您的帮助,谢谢!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    当给组件的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>
    

    【讨论】:

      【解决方案2】:

      Tholle 的回答是正确的。但是,您应该对与状态交互的方式进行一些调整。我已经使用 cmets 重新编写了您的代码,并包含了 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;
      

      【讨论】:

      • 感谢您的提示!
      • 其实这里好像有问题。当我单击“添加问题”按钮时,我收到此错误TypeError: Cannot read property 'state' of undefined
      • 我忘记将 addQuestion 绑定到正确的范围。示例已更新。
      猜你喜欢
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多