onchange输入和设置状态不起作用?

时间:2019-04-08 10:34:14

标签: javascript reactjs

我正在使用react-js处理简单的表单元素。

有三个组成部分:

  1. 应用
  2. TakeInput
  3. 索引

问题是用户将文本放在输入字段setState()函数中时无法正常工作,并且数据未更新。为了进行测试,当我将console.log放置在应用js组件中时,它在控制台上显示未定义。任何人请对此进行排序。我想在状态更新时控制台更新的数据

App.js

import React, { Component } from 'react';
import InputField from './TakeInput';

class App extends Component {
  state = {
    userInp : '',
    outText : ''
  }
  handlechanger2 = (v) => {
    this.setState( () => ({
      userInp: v,
    }))

    console.log(this.userInp);
  }


  render() {
    return (
      <div className="App">
        <InputField changingVal={this.handlechanger2}/>
      </div>
    );
  }
}

export default App;

TakeInput.JS

import React, { Component } from 'react';

class TakeInput extends Component{
    state={
        txt: ''
    }

    handlerChange = (e)=>{
        const { changingVal } = this.props;
        const v = document.getElementById("userInput").value;
        changingVal(v);
        // console.log(e.target.value);
        this.setState({ txt: e.target.value })

    }

    render(){
        return(
            <input type="text" name="userInput" id="userInput" placeholder="Please Enter Text" onChange={this.handlerChange} value={this.txt}/>
        )
    }

}

export default TakeInput;

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';

import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

2 个答案:

答案 0 :(得分:1)

这是关于您正在开发错误的方式。我认为您的文字输入应该在您的父组件中

  • 要读取状态,应使用this.state.abc

import React, { Component } from 'react';

class TakeInput extends Component{

    handlerChange = (e)=>{
        this.props.onChange(e.target.value);

    }

    render(){
        return(
            <input type="text" name="userInput" placeholder="Please Enter Text" onChange={this.handlerChange} value={this.props.txt}/>
        )
    }

}

export default TakeInput;

import React, { Component } from 'react';
import InputField from './TakeInput';

class App extends Component {
  state = {
    userInp : '',
    outText : ''
  }
  handlechanger2 = (v) => {
    this.setState( () => ({
      userInp: v,
    }))

    console.log(this.state.userInp);
  }


  render() {
    return (
      <div className="App">
        <InputField txt={this.state.userInp} onChange={this.handlechanger2}/>
      </div>
    );
  }
}

export default App;

答案 1 :(得分:0)

您正在尝试console.log this.userInp。应该是this.state.userInp

要在最后设置状态之后立即查看更新,您可以执行以下操作:

handlechanger2 = (v) => {
    this.setState( () => ({
      userInp: v,
    }), function(){ console.log(this.state.userInp);}) // set a callback on the setState
  }