父子传参
首先说一下父子传参
父传子:
- 也就是在父组件里面引用子组件,把需要传入值定义到子组件的属性里面
- 比如:需要传入name值
- <Son name1={name} />
- name1属性为自定义属性
- 在子组件里面使用this.props.name1就可以接受到父组件传入的值,可以接受参数
父组件
<Son name={name} />
子组件
const { name } = this.props
return (
<>
<li>父组件的值:{name}</li>
</>
)
子传父:
- 在父组件里面引入子组件,
- 在父组件里面传入回调函数,在子组件里面调用父组件传入的回调函数
父组件
hasName = (e) => {
this.setState({
name:e
})
}
render() {
return (
<>
<Son hasName={ this.hasName} />
</>
)
}
子组件
//自定义函数调用符组件的回调函数,可以传值
sonName = () => {
this.props.hasName("子组件")
}
render() {
return (
<>
<button onClick={this.sonName}>修改父组件的值</button>
</>
)
}
import React, { Component } from 'react'
//引用子组件
import Son from './Son'
export default class extends Component {
constructor(props) {
super(props)
this.state = {
name:"张三"
}
}
//传入子组件的函数
hasName = (e) => {
修改当前页面的state的值
this.setState({
name:e
})
}
render() {
//解构赋值
const { name } = this.state;
return (
<>
//子组件 name传入子组件的内容 hasName为传入子组件的方法,
<Son name={name} hasName={this.hasName} />
</>
)
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。