react混合受控组件

  • 组件可能受上层控制而改变,也可能自身触发而改变。好麻烦。。。
class Searcher extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {content: '',oldPropsContent:''}
  }
  handleClick = (e) => {
    e.preventDefault();
    if (e.keyCode == "13") {
      let content=this.refs.inputer.value.trim()
      this.setState({content: content})
      EventEmitter.dispatch('search', content)
    }
  }
  componentWillReceiveProps(newProps){
    if(newProps.content!=''&&newProps.content!==this.state.oldPropsContent) {
      //比对老数据oldPropsContent,防止被覆盖
      this.setState({content: newProps.content, oldPropsContent: newProps.content})
    }
  }
  handleChange= (e)=>{
    if (e.target.value === this.state.value) return;
    this.setState({content:e.target.value})
  }

  render() {
    return (
      <div className="searcher">
        "请输入查询内容" type="text" onKeyUp={this.handleClick}
               onChange={this.handleChange}
               ref="inputer" value={this.state.content||''}/>
      div>
    );
  }
}

你可能感兴趣的:(前端)