学习目标
- 了解父元素组件与子元素属性之间的通信机制
实例一 子元素传递给父元素数据
import React, { Children } from 'react';
import ReactDOM from 'react-dom';
class ParenetCom extends React.Component {
constructor(props) {
super(props)
this.state = {
childData: "parent..."
}
console.log("parent...")
console.log(this.props)
}
render() {
return (
<div>
<h1>子元素传递给父元素的数据:{this.state.childData}</h1>
<ChildCom setChildData={this.doSetChildData}/>
</div>
)
}
doSetChildData=(data)=> {
this.setState({
childData:data
})
}
}
class ChildCom extends React.Component {
constructor(props) {
super(props)
this.state = {
msg:"hello world"
}
console.log("child...")
console.log(this.props)
}
render() {
return (
<div>
<button onClick={this.sendData}>传递helloworld给父元素</button>
</div>
)
}
sendData=() => {
console.log(this.state.msg)
console.log(this.props)
//将子元素传递给到父元素,实际就是调用父元素传递进来的父元素函数
this.props.setChildData(this.state.msg)
}
}
ReactDOM.render(
<ParenetCom />, // 渲染父元素
document.querySelector('#root') //寻找文件对象
)
子组件通过属性值传递给父组件,父组件通过setState函数修改组件,进而达到传递子组件值的目的。
实例二 匿名函数传递
import React, { Children } from 'react';
import ReactDOM from 'react-dom';
class ParenetCom extends React.Component {
constructor(props) {
super(props)
this.state = {
childData: "parent..."
}
console.log("parent...")
console.log(this.props)
}
render() {
return (
<div>
<h1>子元素传递给父元素的数据:{this.state.childData}</h1>
<ChildCom setChildData={this.doSetChildData}/>
</div>
)
}
doSetChildData=(data)=> {
this.setState({
childData:data
})
}
}
class ChildCom extends React.Component {
constructor(props) {
super(props)
this.state = {
msg:"hello world"
}
console.log("child...")
console.log(this.props)
}
render() {
return (
<div>
<button onClick={this.sendData}>传递helloworld给父元素</button>
<button onClick={() => this.props.setChildData("ddd")}>传递helloworld给父元素</button>
</div>
)
}
sendData=() => {
console.log(this.state.msg)
console.log(this.props)
//将子元素传递给到父元素,实际就是调用父元素传递进来的父元素函数
this.props.setChildData(this.state.msg)
}
}
ReactDOM.render(
<ParenetCom />, // 渲染父元素
document.querySelector('#root') //寻找文件对象
)
通过匿名函数赋给箭头函数实现参数传递。