1.父传子props传值(跟vue一样,只是写法不太一样)
import React, { Component } from 'react'
export default class index extends Component {
render() {
// jsx写法是使用this.props接受
console.log('props', this.props)
const { name, age } = this.props
return (
<div>
{name}---{age}
</div>
)
}
}
2.子传父
//父组件
import React, { Component } from 'react'
import Child from './child'
export default class toParent extends Component {
state = {
parentMsg: '',
}
getChildMsg = (data) => {
console.log('data', data)
this.setState({
parentMsg:data
})
}
render() {
const { parentMsg } = this.state
return (
<div>
父组件:{parentMsg}
<br />
<Child getMsg={this.getChildMsg}></Child>
</div>
)
}
}
//子组件
import React, { Component } from 'react'
export default class toParent extends Component {
state = {
msg: '子组件传值给父组件',
}
handleClick=()=>{
this.props.getMsg(this.state.msg)
}
render() {
return (
<div>
子组件
<button onClick={this.handleClick}>
点击传给父组件
</button>
</div>
)
}
}
注意:直接通过create-react-app模式创建的,默认就是StrictMode下。StrticMode默认会执行两次render,来检测你的render函数有没有副作用。
去掉即可