react学2-父子组件通信

react单项数据流动

父组件可以传递数据给子组件

class Child extends React.Component {
  render() {
    return (
        <div>{this.props.name}</div>
    );
  }
}

class Father extends React.Component {
  render() {
    return (
      <Child name={"Mr yang"} />
    );
  }
}
ReactDOM.render(<Father />, document.getElementById('root'));

但是这样如果想在父组件修改name的属相值,子组件也同步修改。这块就需要用到state了。
react state props可以去查资料看看两者的区别。

class Child extends React.Component {
  constructor(props) {
    super(props);
    //子组件通过父组件传递的值初始化state
    this.state={name : this.props.name}
  }
  //查阅上一篇文章了解一下
  componentWillReceiveProps(nextProps){
    this.setState({name : nextProps.name})
  }
  render() {
    return (
        <div>{this.state.name}</div>
    );
  }
}

class Father extends React.Component {
  //设置state
  state = {name:"Mr Yang"}
  //必须通过setState来修改
  click(){
    this.setState({name:"Mr Muyi" });
  }
  render() {
    return (
      <div>
        <Child name={this.state.name} />
        <button onClick={this.click.bind(this)}>click</button>
      </div>
    );
  }
}
ReactDOM.render(<Father />, document.getElementById('root'));

父组件通过refs调用子组件实例。具体查阅官网资料。
https://reactjs.org/docs/refs-and-the-dom.html

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

  focusTextInput() {
    console.log('hello')
  }
  render() {
    return (
      <div>
        <input type="text"/>
      </div>
    );
  }
}

class AutoFocusTextInput extends React.Component {
  constructor(props) {
    super(props);
    //初始化ref
    this.textInput = React.createRef();
  }
  //完成加载的时候调用子组件方法
  componentDidMount() {
    this.textInput.current.focusTextInput();
  }

  render() {
    return (
      <CustomTextInput ref={this.textInput} />
    );
  }
}

ReactDOM.render(<AutoFocusTextInput />, document.getElementById('root'));

子组件通过调用父组件注册函数,调用父组件方法

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

  getFather() {
    console.log('hello')
    //调用父组件方法
    this.props.MakeMoney('who are you');
  }
  componentDidMount(){
    this.getFather();
  }
  render() {
    return (
      <div>
        <input type="text"/>
      </div>
    );
  }
}

class AutoFocusTextInput extends React.Component {
  constructor(props) {
    super(props);
  }
 //供子组件调用
  MakeMoney(msg){ 
    console.log(msg);
  }

  render() {
    return (
      <CustomTextInput  MakeMoney={this.MakeMoney} />
    );
  }
}

ReactDOM.render(<AutoFocusTextInput />, document.getElementById('root'));
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容