React Controlled Components未正确接收输入

时间:2016-01-04 16:33:09

标签: javascript reactjs

我无法弄清楚受控组件。几乎完全按照文档中的示例执行所有操作:https://facebook.github.io/react/docs/forms.html#controlled-components

只会有一个输入字符进入输入。在下一个字符输入时,前一个字符输入被替换。当我输入'asdf'时,我明白了:

changeName a
changeName s
changeName d
changeName f

这是我的代码:

export class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.handleChangeName = this.handleChangeName.bind(this)
    this.handleChangeDescription = this.handleChangeDescription.bind(this)
    this.state = ({name:'',description:''})
  }

  shouldComponentUpdate (nextProps, nextState) {
    return false
  }

  handleChangeName(event) {
    console.log('changeName',event.target.value)
    this.setState({name: event.target.value.substr(0, 8)});
  }

  handleChangeDescription(event) {
    this.setState({description: event.target.value.substr(0, 140)});
  }

  render () {
    return (
    <Row>
      <Col xs={12} lg={12} className="beacon-fields">
        <Input id="name" help="Name" className="form-control" type="text" value={this.state.name} onChange={this.handleChangeName} />
        <Input id="description" help="Description" className="form-control" type="text" value={this.state.description} onChange={this.handleChangeDescription} />
      </Col>
    </Row>
  )
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题相当明显。 shouldComponentUpdate方法阻止了渲染执行,这意味着输入没有出现在输入字段中。解决方案很简单:

shouldComponentUpdate (nextProps, nextState) {
  if (this.state !== nextState) {
    return true
  }    
  return false
}