父组件给子组件传值
父组件:使用子组件时,直接传入值(attr=value)
子组件:类组件通过this.props.attr获取父组件传来的值,函数组件通过props.attr获取父组件传来的值
//父组件
import React from "react";
import Message from '../Message/messageIndex'
export default class City extends React.Component{
constructor(){
super()
this.state={
name:'父组件'
}
}
render(){
return (
<div>
<Message name={this.state.name}></Message>
</div>
)
}
}
//子组件
import React from "react";
export default class Message extends React.Component{
constructor(props){
super(props)
this.state={
info:'子组件'
}
}
render(){
return (
<div>{this.props.name}</div>
)
}
}
子组件给父组件传值
父组件:给子组件传一个函数,通过子组件调用并传入参数,获取子组件的值,将值保存至state中
子组件:通过this.props(函数组件通过props)获取整个函数,然后在参数中传入待传递的值
//父组件
import React from "react";
import Message from '../Message/messageIndex'
export default class City extends React.Component{
constructor(){
super()
this.state={
name:'父组件',
message:''
}
}
getMessage=(msg)=>{
this.setState({
message:msg
})
}
render(){
return (
<div>
{/* <Message name={this.state.name} getInfo={this.getMessage}></Message> */}
<Message getInfo={this.getMessage}></Message>
<h4>子组件传来的值:{this.state.message}</h4>
</div>
)
}
}
//子组件
import React from "react";
export default class Message extends React.Component{
constructor(props){
super(props)
this.state={
info:'我是子组件'
}
this.props.getInfo(this.state.info)
}
render(){
return (
// <div>{this.props.name}</div>
<div></div>
)
}
}
兄弟组件传值
子组件A===》父组件===》子组件B
同上
祖孙组件传值
在单独的js文件中创建context
在需要传值与接收值的祖孙组件中引入创建的context
//context.js
import React from "react";
export const ThemeContext = React.createContext('none');
export default function(){}
//爷爷
import React from "react";
import Message from '../Message/messageIndex'
import {ThemeContext} from '../../Context/context'
class City extends React.Component{
constructor(){
super()
this.state={
name:'父组件',
message:'',
sonson:'wuwuwu'
}
}
// getMessage=(msg)=>{
// this.setState({
// message:msg
// })
// }
render(){
return (
<div>
<ThemeContext.Provider value={this.state.sonson}>
<Message></Message>
</ThemeContext.Provider>
</div>
)
}
}
City.contextType = ThemeContext
export default City
//孙子
import React from "react"
import {ThemeContext} from '../../Context/context'
class MyButton extends React.Component {
constructor(props){
super(props)
}
render() {
return <div style={{color:'red'}}>{this.context}</div>
}
}
MyButton.contextType=ThemeContext
export default MyButton