react性能提升原理:虚拟DOM

react把真是的DOM tree,转化成virtual DOM,每次数据更新后,重新计算virtual DOM并与上一次的作对比,然后对发生改变的部分进行批量更新。从此性能得到提升。

正文:通信

父——>子 使用props。

子组件中(我的示例中,父组件1个,子组件3个):

class Input extends React.Component{ //input子组件,class类型的组件
  constructor(props) {
    super(props);
    this.onChangeFunc = this.onChangeFunc.bind(this)
    this.onBlur = this.onBlur.bind(this)
  }
  render (){
    return <input className={this.props.color} 
                  value = {this.props.value} 
                  onChange={this.onChangeFunc}
                  onBlur = {this.onBlur}
            />
  }
  onChangeFunc(e){
    this.props.inputValueFunc(e.target.value)  //这里使用了从父组件传进来的方法
  }
  onBlur(e){
    var value = parseInt(e.target.value,10);
    if (value) {
        alert('你输入了数字')
    } else {
      alert('你输入了字符串')
    }
  }
}

class Button extends React.Component{
  render(){
    return <button className={this.props.color}>{this.props.name}</button>
  }
}

function Hello(props){  //props是从父组件中传进来的。
  return <div className={props.color}>{props.children}</div>
}

上面示例代码中,有3个子组件,其中前两个是class类组件,props是从父组件中传进来的对象。

 

父组件中:

class App extends Component {
  constructor(props){
    super(props)
    this.state = {value:'please input something'}
    this.inputValueFunc = this.inputValueFunc.bind(this)
  }
  inputValueFunc(value){
    this.setState({
      value: value
    })
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>

        <Hello color='blue'>
        <h3>啦啦啦</h3>
        <p>Thank you for visiting !</p>
        </Hello>

        <Input inputValueFunc={ this.inputValueFunc } value={this.state.value} color='blue'/> //传入的props可以有方法。

        <Button color='blue' name='submit' value = {this.state.value}></Button> // 在引入子组件时候,传入props,就是上面的属性。
      </div>
    );
  }
}

子——>父

react中,子不能直接向父通信,解决办法是:

直接把要传的数据保存在父组件的state中,例如本例子中APP组件的state,然后在父组件中写方法,用来改变自己的state。把方法inputValueFunc传给子组件,子组件调用该方法,并把数据作为参数传给inputValueFunc。

子——>子

寻找最近的父组件,通过父组件通信。或者使用context,但是官方并不推荐,有可能移除(感觉不是亲生的啊,官方文档各种理由不建议使用。。。)。因此,对于大的项目,还是使用状态管理工具吧。

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!