1、父组件向子组件传值
父组件向子组件传值一般采用props属性传递
父组件:
import React from 'react' import Child from './Child' const dataList = [ { id: '001', value: '张三' }, { id: '002', value: '李四' } ] const Parent = props => { return ( <ul> <Child dataList={dataList}></Child> </ul> ) } export default Parent
子组件:
import React from 'react' const Child = props => { return ( <React.Fragment> { props.dataList.map(item => <li key={item.id}>{item.value}</li>) } </React.Fragment> ) } export default Child
2、子组件向父组件传值
子组件调用父组件传过来的回调函数来更改父组件的state
父组件
import React, { useState } from 'react' import Child from './Child' const Parent = props => { const [count, setCount] = useState(0) return ( <Child count={count} setCount={setCount}></Child> ) } export default Parent
子组件
import React from 'react' const Child = props => { return ( <React.Fragment> <button onClick={() => {props.setCount(props.count-1)}}>-</button> <span>{props.count}</span> <button onClick={() => {props.setCount(props.count+1)}}>+</button> </React.Fragment> ) } export default Child
3、跨级组件传值(祖孙组件)
context是一个全局变量,像是一个大容器,在任何地方都可以访问到,我们可以把要通信的信息放在context上,然后在其他组件中可以随意取到;
但是React官方不建议使用大量context,尽管他可以减少逐层传递,但是当组件结构复杂的时候,我们并不知道context是从哪里传过来的;而且context是一个全局变量,全局变量正是导致应用走向混乱的罪魁祸首.
父组件
import React, { useState } from 'react' import Child from './Child' export const MyContext = React.createContext('hello') const Parent = props => { return ( <MyContext.Provider value="world"> <Child /> </MyContext.Provider> ) } export default Parent
子组件
import React from 'react' import Son from './Son' const Child = props => { return ( <Son /> ) } export default Child
孙组件
import React from 'react' import { MyContext } from './Parent' export default class Son extends React.Component { render() { return ( <MyContext.Consumer> { context => <div>{context}</div> } </MyContext.Consumer> ) } }
参考:
https://blog.csdn.net/xingfuzhijianxia/article/details/86151243
https://www.cnblogs.com/qinney1109/p/11202085.html