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;
本文通过实战案例展示了如何使用 React 的 Context API 在组件间传递数据,避免了繁琐的逐级 props 传递,简化了跨层级组件间的通信。文章首先创建了一个提供数据的父组件,并在其中定义了 getChildContext 方法来传递数据,接着展示了如何在子孙组件中通过 contextTypes 接收这些数据。
563

被折叠的 条评论
为什么被折叠?



