巩固React基础
1.父传子数据传递
Props
单向流动,不能子传父,可以是任意类型,也可以设置默认值。
父传子比较简单:
1:在父元素中设置属性,并将该属性传值到子元素中。
2:子元素通过props接收值
3:在父元素中写好函数改变该值,从而实现父控制子元素
class ParentDom extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: true,
}
}
changeShow = () => {
this.setState({
isShow: !this.state.isShow,
})
}
render() {
return (
<div>
<button onClick={this.changeShow}>是否显示?</button>
//在子组件中 传递isShow属性
<ChildrenDom isShow={this.state.isShow}></ChildrenDom>
</div>
)
}
}
class ChildrenDom extends React.Component {
constructor(props) {
super(props)
}
render() {
let strClass = null
//通过props接收父元素的isShow属性
if (this.props.isShow) {
strClass = ' active'
} else {
strClass = ''
}
return (
<div className={'content' + strClass}>
<h1>子元素</h1>
</div>
)
}
}
.content {
width: 400px;
height: 400px;
background-color: salmon;
display: none;
}
.active {
display: block;
}
2.子传父数据传递
Props
也可以传递函数,通过调用父元素的函数实现子元素操作父元素数据,从而达到传输数据给父元素
子传父稍微复杂在于:
1:同样是在父元素中设置一个属性值,但此时需要设置一个函数,这个函数需要传入一个data,用于修改父元素中属性的值
2:与此同时,子元素中也需要设置一个属性值,这个属性值是用于修改父元素的值
3:将父元素中的修改值函数传递给子元素
4:子元素同样也创建一个函数,用于调用父元素传给子元素的函数。并将子元素的值通过这个函数赋值给父元素
class Parent2 extends React.Component {
constructor(props) {
super(props)
this.state = {
ChildData: '芜湖',
}
}
render() {
return (
<div>
<h1>子传父的数据为:{this.state.ChildData}</h1>
//将父元素setState的函数传给子元素
<Child setChildData={this.setChildData}></Child>
</div>
)
}
//父元素中设置state的值里 需要传入一个data,这样就可以接收其他地方传入的值
setChildData = (data) => {
this.setState({
ChildData: data,
})
}
}
class Child extends React.Component {
constructor(props) {
super(props)
this.state = {
msg: '起飞',
}
}
render() {
return (
<div>
<button onClick={this.sendData}>传递test给父元素</button>
</div>
)
}
sendData = () => {
//这里通过props可以拿到父元素的setchildData
//console.log(this.props)
//通过调用父元素的函数,将子元素的值传入去改变父元素的属性值
this.props.setChildData(this.state.msg)
}
}