javascript - 为什么 event.target.value 只捕获字符串输入中的第一个字母

标签 javascript reactjs

一旦我开始将 Prop 从父级传递到子级再到子级,我就遇到了这个问题,其中 getQuestion 函数只能获取输入的第一个字母,此外在输入字段中什么也没有显示。

之前,当我的代码只是父子对子时,它就可以工作。

我想知道到底发生了什么,因为我已经尝试通过控制台日志记录进行调试,并且我所知道的是它只注册了第一个字母。

这个问题没有帮助,因为我没有拼写错误onChange

Can't type in React input text field

App.js

class App extends Component {
  constructor(props){
    super(props);



    this.getPostId = this.getPostId.bind(this);
    this.getQuestion = this.getQuestion.bind(this);
    this.makePost = this.makePost.bind(this);
    this.getBody = this.getBody.bind(this);
    this.getPostType = this.getPostType.bind(this);
    this.getImgSrc = this.getImgSrc.bind(this);
    this.submitPost = this.submitPost.bind(this);
    this.formOpen = this.formOpen.bind(this);
    this.formClose = this.formClose.bind(this);

    this.back = this.back.bind(this);
    this.showPost = this.showPost.bind(this);
    this.renderPosts = this.renderPosts.bind(this);

    //Answer/Response methods
    this.makeAnswer = this.makeAnswer.bind(this);
    this.getAnswer = this.getAnswer.bind(this);
    this.submitAnswer = this.submitAnswer.bind(this);

    this.state = {
      posts: [],

        answers: [],

      question: '',
      body: '',
      postType: 'Question',
      imgSrc: '',
      form: false,
      openedPost: null,
      answer: '',
      favorited: false,

      //sign up
      email:'',
      password: '',
      user: null

    }

}
getQuestion(event) {
  event.preventDefault();
  this.setState({ question:event.target.value });
}


render() {


    return (

      <Router>
        <div className="container">
          <Route
                  exact path={"/"}
                  component={() => <Home />}
          />

          <Route
                  exact path={"/home"}
                  component={() => <Home />}
          />

          <Route
                exact path={"/signup"}
                component={() => <SignUp />}
          />

          <Route
                exact path={`/dashboard`}
                component={() =>
                  <Dashboard back={this.back}
                    form={this.state.form}
                      openedPost={this.state.openedPost}
                        renderPosts={this.renderPosts}
                          formClose={this.formClose}
                            formOpen={this.formOpen}
                              posts={this.state.posts}
                                getPostId={this.getPostId}
                                  getQuestion={this.getQuestion}
                                    makePost={this.makePost}
                                      getBody={this.getBody}
                                        getPostType={this.getPostType}
                                          getImgSrc={this.getImgSrc}
                                              submitPost={this.submitPost}
                                                test={this.test}
                                                  question={this.state.question}

                />}
              />



                <Route
                      exact path={`/dashboard/post${this.state.openedPost}`}
                      component={() =>
                        <SinglePost posts={this.state.posts}
                                      openedPost={this.state.openedPost}
                                       getAnswer={this.getAnswer}
                                        makeAnswer={this.makeAnswer}
                                          submitAnswer={this.submitAnswer}
                                            showAnswers={this.showAnswers}
                                              renderAnswers={this.renderAnswers}
                                                renderFavorite={this.renderFavorite}
                                                  userFavorited={this.userFavorited}
                                                    back={this.back}

                      />
                    }

                    />






      </div>
    </Router>
    );
  }

Dashboard.js

import React, { Component } from 'react';
import Navagationbar from  '../../components/Navigation/Navagationbar';
import Header from  '../../components/Header/Header';
import SignUpButton from  '../../components/SignUp/SignUpButton';
import AddPostForm from './AddPostForm';
import './styles.css';

import {
  Link
} from 'react-router-dom'

class Dashboard extends Component {
  render() {


    let renderedPosts = null;



    let createPostButton =  <div className="container" ><button className="button-primary" onClick={this.props.formOpen}> Create Post </button> </div>;

    if(this.props.openedPost) {
      renderedPosts = null;
      createPostButton = null;
    }
    else {
      renderedPosts = this.props.renderPosts();
    }

        let createPostForm = null;
        const openedForm = this.props.form;
        if(openedForm) {
        createPostForm =
              <AddPostForm
                formClose={this.props.formClose}
                    posts={this.props.posts}
                      getPostId={this.props.getPostId}
                        getQuestion={this.props.getQuestion}
                          makePost={this.props.makePost}
                            getBody={this.props.getBody}
                              getPostType={this.props.getPostType}
                                getImgSrc={this.props.getImgSrc}
                                    submitPost={this.props.submitPost}
                                      question={this.props.question}

                                    />

          createPostButton = null;
        }
        console.log("OPENED FORM IS " + openedForm)
    return (
    <div >
      <SignUpButton />
      <Header />
      <button onClick={this.props.test}/>
      {this.props.openedPost ? null : <Navagationbar />}



        {createPostForm}
        <div className="row">
          <div>
            {createPostButton}
          </div>
        </div>

        <div className="row">



        </div>
      <div className="row">
        <div className="twelve columns">
            {renderedPosts}
        </div>
      </div>

    </div>
    );
  }
}


export default Dashboard;

AddPostForm.js

import React, { Component } from 'react';
import './styles.css';

class AddPostForm extends Component {
    render() {
    return(
      <div className="container">



      <div className="row">
            <div className="six columns">
              <label>Post Title</label>
                <input onChange={this.props.getQuestion} value={this.props.question} className="u-full-width" type="search" placeholder="title" id="exampleEmailInput"/>
            </div>

              <div className="six columns">
                <label>Post Type</label>
                  <select value={this.props.type} onChange={this.props.getPostType} className="u-full-width">
                    <option value="Question">Question</option>
                    <option value="Discussion">Discussion</option>

                 </select>
              </div>
        </div>
            <div className="row">
              <div className="twelve columns">
                <label>Post</label>
                  <textarea onChange={this.props.getBody}  className="u-full-width" placeholder="get some clout" id="postMessage"></textarea>
                <label>
                  <span>Image Link</span> <br />
                    <input type="search"  onChange={this.props.getImgSrc}/>
                </label>
                  <input className="button-primary" type="button" value="submit" onClick={this.props.submitPost}/>
                  <button onClick={this.props.formClose}>Cancel </button>
               </div>
            </div>

    </div>

    );
  }
}

export default AddPostForm;

编辑: 从 getQuestion 中删除 event.preventDefault() 后,我可以输入,但为什么输入字段在输入一个字母后就失去焦点。

是因为每次我输入输入字段后都会重新渲染吗?

编辑:根据要求添加了大部分代码。

我认为这已经足够了,如果您需要其余功能,请告诉我。

最佳答案

浏览完代码后,我注意到所有方法都来自根级组件App。在这种情况下,当您在帖子标题输入字段中键入内容时,它会立即调用父 getQuestion 方法,该方法通过重新渲染页面来设置状态,从而导致输入字段失去焦点。

方法一:
要解决此问题,我建议您通过允许 AddPostForm 管理自己的状态来维护其状态。

import React, { Component } from 'react';

class AddPostForm extends Component {
  state = {
    question: ""
  }

  setQuestion = (event) => {
    this.setState({
      question: event.target.value
    });
  }

  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="six columns">
            <label>Post Title</label>
            <input
             onChange={this.setQuestion} // note change
             value={this.state.question} // note change
             className="u-full-width"
             type="search"
             placeholder="title"
             id="exampleEmailInput"
            />
          </div>
          ...
        </div>
      </div>
    );
  }
}

export default AddPostForm;

方法2:
App.js render 方法中,我做了一些更改,允许您将 props 传递给子组件,而文本字段不会失去焦点。

render() {
    return (

      <Router>
        <div className="container">
          <Route
            exact
            path="/"
            component={Home}
          />

          <Route
            exact
            path="/home"
            component={Home}
          />

          <Route
            exact
            path="/signup"
            component={SignUp}
          />

          <Route
            exact
            path="/dashboard"
            render={(props) =>
              <Dashboard
                {...props}
                back={this.back}
                body={this.state.body}
                form={this.state.form}
                openedPost={this.state.openedPost}
                renderPosts={this.renderPosts}
                formClose={this.formClose}
                formOpen={this.formOpen}
                posts={this.state.posts}
                getPostId={this.getPostId}
                getQuestion={this.getQuestion}
                makePost={this.makePost}
                getBody={this.getBody}
                getPostType={this.getPostType}
                getImgSrc={this.getImgSrc}
                submitPost={this.submitPost}
                test={this.test}
                question={this.state.question}
              />
            }
          />

          <Route
            exact
            path={`/dashboard/post${this.state.openedPost}`}
            render={(props) =>
              <SinglePost
                {...props}
                posts={this.state.posts}
                openedPost={this.state.openedPost}
                getAnswer={this.getAnswer}
                makeAnswer={this.makeAnswer}
                submitAnswer={this.submitAnswer}
                showAnswers={this.showAnswers}
                renderAnswers={this.renderAnswers}
                renderFavorite={this.renderFavorite}
                userFavorited={this.userFavorited}
                back={this.back}
              />
            }
          />
        </div>
      </Router>
    );
  }

dashboardRoute 中,我从使用 Routecomponent 属性更改为使用 改为 render 属性。这解决了这个问题。

Edit Q 47857536 SO

关于javascript - 为什么 event.target.value 只捕获字符串输入中的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47857536/

相关文章:

javascript - 如何处理动态内容的点击事件?

javascript - Bootstrap 模式中的 Rails link_to

reactjs - 停止重新渲染 react 功能组件

javascript - 从 Postgres DB 获取 PNG 文本并将图像发送到前端 React

html - React Bootstrap 调整文本输入的宽度

javascript - 函数调用前的@是什么意思?

javascript - HTTP post 请求 - AngularJS 和 JQuery 之间的区别

javascript - 如何使用 spawn 在 Node js 中暂停进程

javascript - CasperJS中evaluate()中的DOM元素缺少click()函数

android - 如何使用 react native 集市显示来电