一、组件传值:
1、
2、Context: https://www.cnblogs.com/littleSpill/p/11221538.html
概念:Context提供了一种方式,能够让数据在组件树中传递,而不必一级一级手动传递。
个人理解: 感觉有点想,父组件 把值给第三方保管(Context对象),孙组件,从第三方那拿值。但是这种处理,感觉不好。
一般组件,都是分不同的组件的文件的。父组件 和 孙组件要使用同一个context对象,所以,这个context 要单独放在一个文件中,供这个两个组件使用。
import React, { Component, createContext } from 'react'; const BatteryContext = createContext(); class Leaf extends Component { // 声明一个孙组件 render() { return ( <BatteryContext.Consumer> // Consumer内 回调函数,值作为参数传递进来 { battery => <h1>Battery : {battery}</h1> } </BatteryContext.Consumer> ) } } class Middle extends Component { // 声明一个子组件 render() { return <Leaf /> } } class App extends Component { // 声明一个父组件 render(){ return ( <BatteryContext.Provider value={690}> <Middle /> </BatteryContext.Provider> ); } } export default App;
最后再提示一下大家,不要滥用context,不然会影响组件的独立性。 如果一个组件中只使用一个Context的话,就可以使用contextType代替Consumer。详见 https://www.cnblogs.com/littleSpill/p/11221817.html
二、