从状态不正常更新输入值

时间:2019-12-12 07:27:16

标签: javascript reactjs

我遇到输入问题,在这种情况下,选择输入在状态更新时不会更新。谁能告诉我我要去哪里错了?

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        selectType:'1'
    }
   }

    onChangeEndpointType(event) {
        this.setState=({
          selectType:event.target.value, 
        })
    }

    render() {
        return (
            <select name="selecttype" value={this.state.selectType} onChange={() => this.onChangeEndpointType(event)}>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
            </select>
        )}
  }

3 个答案:

答案 0 :(得分:1)

我相信setState有错别字,请尝试以下操作:

 onChangeEndpointType(event) {
     // setState 
     this.setState({
       selectType:event.target.value, 
     })
    }

答案 1 :(得分:0)

您必须将函数的此与构造函数的此绑定: 投票是否可行

class Page extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        selectType:'1'
    }
    this.onChangeEndpointType = this.onChangeEndpointType.bind(this);
}

    onChangeEndpointType(event) {
        this.setState=({
        selectType:event.target.value, 
        })
    }

    render() {
        return (
            <select name="selecttype" value={this.state.selectType} onChange={() => this.onChangeEndpointType(event)}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            </select>
        )}
}

答案 2 :(得分:0)

您的代码中有很多bug

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectType:'1'
    }
  }

  onChangeEndpointType(event) {
    this.setState({
      selectType:event.target.value, 
    })
  }
  render() {
    return (
      <div className="App">
        <select name="selecttype" value={this.state.selectType} onChange={(event) => this.onChangeEndpointType(event)}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
        </select>
      </div>
    );
  }
}

一个是setState语法错误

this.setState({
  selectType:event.target.value, 
})

另一件事是您在onChange回调中具有通过事件

onChange={(event) => this.onChangeEndpointType(event)}