React Native

React 父与子之间传递

2017-11-16  本文已影响13人  踏云小子

props

image.png
// 父元素
export default class Father extends React.Component {
  render() {
    return (
        <Child handleClickOrder={this.handleClickOrder.bind(this)} />
    )
  }

  handleClickOrder(){
  }
}
// 子元素
export default class Child extends React.Component {
  render() {
    return (
        <div onClick={this.props.handleClickOrder}>          
        </div>
    )
  }
}
// 父元素
export default class Father extends React.Component {
  render() {
    return (
        <Child handleClickOrder={this.handleClickOrder.bind(this)} />
    )
  }

  handleClickOrder(Id){
    console.log(Id);
  }
}
// 子元素
export default class Child extends React.Component {
  render() {
    return (
        <div onClick={()=>{this.props.handleClickOrder(this.props.data.id)}}>          
        </div>
    )
  }
}

如上所示,父元素获取到子元素的Id,注意,子元素的onClick不能写成onClick={this.props.handleClickOrder(this.props.data.id)},会造成重复渲染

state

ref

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}
image.png
import React from 'react'
import WWTextView from './WWTextView'

export default class NotFound extends React.Component {

  render() {
    console.log('render');
    return (
        <div>
          <WWTextView
              ref={(input)=>{this.textInput=input}}
          />
        </div>
    )
  }

  componentDidMount(){
    this.textInput.focusTextInput();
  }

}

自定义组件WWTextView如下

import React from 'react'

export default class WWTextView extends React.Component {

  focusTextInput() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
    console.log('haha');
  }

  render() {
    console.log('render');
    return (
        <div>
          <input
              type="text"
              ref={(input) => { this.textInput = input; }} />
          <input
              type="button"
              value="Focus the text input"
              onClick={this.focusTextInput.bind(this)}
          />
        </div>
    )
  }

}

props与state区别

名称 props state
使用场景 父组件传值给子组件 表示组件内部状态,不限父组件、子组件
重新渲染 父组件传给子组件的props发生变化,也会导致子组件的重新渲染 state变化导致组件重新渲染
用途 用于放置初始化数据,且一直不变的 用于放置那些组件变化而更新的数据
上一篇 下一篇

猜你喜欢

热点阅读