父组件向子组件传值
1.父组件中定义要传的值
import React, { Component } from "react"
import "./assets/css/app.css"
// 引入组件A
import ComentA from "./components/ComentA"
class App extends Component {
constructor(props) {
super(props)
this.state = {
msg: "我是父组件的值"
}
}
render () {
return (
<div>
<span>这是app组件</span>
//向子组件传递值,前面的变量名可自定义
<ComentA msg={this.state.msg}></ComentA>
</div>
)
}
}
export default App
2.在子组件中接收父组件传递过来的值
// import React, { Component } from "react"
//类组件的使用方法
// class ComentA extends Component {
// constructor(props){
// super(props)
// this.state={
// }
// }
// render () {
// return (
// <>
// <div>
// <p>我是组件A</p>
// <p>{this.props.msg}</p>
// </div>
// </>
// )
// }
// }
//函数组件的使用方法
function ComentA (props) {
//msg要和父组件定义的变量名相同
const { msg } = props
return (
<>
<div>
<p>我是组件A</p>
<p>父组件传的值:{msg}</p>
</div>
</>
)
}
export default ComentA
子组件向父组件传值
1.子组件通过调用父组件函数传递值
let state = {
coment: "我是组件A的值"
}
function ComentA (props) {
const { msg, run } = props
function getComent () {
// 调用父组件传递过来的回调函数 并传入参数
run(state.coment)
}
return (
<>
<div>
<p>我是组件A</p>
<p>{msg}</p>
<button onClick={getComent}>给父组件传值</button>
</div>
</>
)
}
export default ComentA
2.父组件通过函数回调取出子组件传过来的值
class App extends Component {
constructor(props) {
super(props)
this.state = {
msg: "我是父组件的值"
}
}
{/* 通过回调函数接收子组件的值*/}
run = (data) => {
// 打印子组件传过来的值
console.log(data)
}
render () {
return (
<div>
<span>这是app组件</span>
{/*1.msg变量值传给子组件 2.回调函数传给子组件 */}
<ComentA msg={this.state.msg} run={this.run}></ComentA>
</div>
)
}
}
405

被折叠的 条评论
为什么被折叠?



