持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情
React Props
父组件传递给子组件数据,单相流动,不能子组件传递给父组件。
Props的传值可以是任意的类型。
Props可以设置默认值
HelloMessge.defaultProps={name:"老王",msg:"helloworld"}
注意:Props可以传递函数,props可以传递父元素的函数,就可以修改父元素的state,从而达到传递数据给父元素。
父传子案例:
//在父元素中使用state中控制子元素props,从而达到父元素传递数据给子元素
class PrentCom extends React.Component{
constructor(props){
super(props);
this.state={
isActive:true
}
this.changeShow=this.changeShow.bind(this)
}
render(){
return(
<div>
<button onClick={this.changeShow}>控制子元素显示button>
<ChildCom isActive={this.state.isActive} />
div>
)
}
changeShow(){
this.setState({
isActive:!this.state.isActive
})
}
}
class ChildCom extends React.Component{
constructor(props){
super(props)
}
render(){
let strClass = null;
if(this.props.isActive){
strClass = ' active'
}else{
strClass = ''
}
return (
<div className={"content"+strClass}>
<h1>我是子元素h1>
div>
)
}
}
React数据传递:子传父
调用父元素的函数,从而操作父元素的数据,实现数据从子元素传递至父元素 子传父案例:
import React from 'react';
import ReactDOM from 'react-dom';
//子传父
class ParentDoc extends React.Component{
constructor(props){
super(props)
this.state={
childData:null
}
}
render(){
return(
<div>
<h1>子元素传递给父元素的数据:{this.state.childData}h1>
<ChildCom setChildDate={this.setChildDate} />
</div>
)
}
setChildDate=(data)=>{
this.setState({
childData:data
})
}
}
class ChildCom extends React.Component{
constructor(props){
super(props)
this.state={
msg:"helloworld"
}
}
render(){
return(
<div>
<button onClick={this.sendData}>传递给父元素button>
<button onClick={()=>{this.props.setChildDate(this.state.msg)}}>匿名函数传递给父元素button>
div>
)
}
/*
sendData=()=>{
//将子元素传递给父元素,实际就是调用父元素传递进来的父元素函数
this.props.setChildDate(this.state.msg)
}*/
}
ReactDOM.render(<ParentDoc />, document.querySelector("#root"));