react学2-父子组件通信

react单项数据流动

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

class Child extends React.Component {
  render() {
    return (
        
{this.props.name}
); } } class Father extends React.Component { render() { return ( ); } } ReactDOM.render(, 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 (
        
{this.state.name}
); } } class Father extends React.Component { //设置state state = {name:"Mr Yang"} //必须通过setState来修改 click(){ this.setState({name:"Mr Muyi" }); } render() { return (
); } } ReactDOM.render(, 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 (
      
); } } class AutoFocusTextInput extends React.Component { constructor(props) { super(props); //初始化ref this.textInput = React.createRef(); } //完成加载的时候调用子组件方法 componentDidMount() { this.textInput.current.focusTextInput(); } render() { return ( ); } } ReactDOM.render(, 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 (
      
); } } class AutoFocusTextInput extends React.Component { constructor(props) { super(props); } //供子组件调用 MakeMoney(msg){ console.log(msg); } render() { return ( ); } } ReactDOM.render(, document.getElementById('root'));

你可能感兴趣的:(react学2-父子组件通信)