React之使用context传递数据

react中当要从父组件给子孙组件传递数据时 如果用props传递 则需要一级一级传递 而如果用context时 则可以在父组件中加入getChildContext函数 并声明需要传递的数据 在需要接受到数据的组件中声明变量类型Test.contextTypes = {test : PropTypes.string} 

Example:

//父组件
import React, { Component,PropTypes } from 'react';
import Son from './Son';

class App extends Component {

  getChildContext() {
      return {test: "hello"};
  }

  render() {
      return (
          <div className="App" style={{border:'1px solid red',width:'30%',margin:'50px auto',textAlign:'center'}}>
              <p style={{padding:'0',margin:'0'}}>父组件</p>
              <Son/>
          </div>
      );
  }
}

App.childContextTypes = {
    test: PropTypes.string
};

export default App;
//子组件
import React, { Component,PropTypes } from 'react';
import Grandson from './Grandson';

class SubChildApp extends Component {
    render() {
        console.log('this.context',this.context);

        return (
            <div className="son" style={{border:'1px solid blue',width:'60%',margin:'50px auto',textAlign:'center'}}>
                <p>子组件,获取父组件的值:{this.context.test}</p>
                <Grandson/>
            </div>
        );
    }
}
SubChildApp.contextTypes = {
    test: PropTypes.string
};
export default SubChildApp;
//孙组件
import React, { Component,PropTypes } from 'react';
class App extends Component {
    render() {
        console.log('this.context:',this.context);
        return (
            <div className="son" style={{border:'1px solid green',width:'60%',margin:'50px auto',textAlign:'center'}}>
                <p>孙组件,获取传递下来的值:{this.context.test}</p>
            </div>
        );
    }
}
App.contextTypes = {
    test: PropTypes.string
};
export default App;

猜你喜欢

转载自blog.csdn.net/margin_0px/article/details/81448382