學習目標
Props
父傳遞給子組件數據,單向流動,不能子組件傳遞給父組件。
props的傳值,可以是任意類型。
Props默認值設置
HelloMessage.defaultProps = {name:"Bill"}
注:props可以傳遞函數,props可以傳遞父元素的函數,可以修改父元素的state,從而達到傳遞數據給父元素。
實例分析
import React, { Children } from 'react';
import ReactDOM from 'react-dom';
import './test.css'
// 在父元素中使用state控制子元素props,將父元素數據傳遞給子元素
class ParenetCom extends React.Component {
constructor(props) {
super(props)
this.state = {
isActive: "true"
}
this.onShow = this.onShow.bind(this); //必須要寫
}
render() {
return (
<div>
<button onClick={this.onShow}>控制子元素顯示</button>
<ChildCom isActive={this.state.isActive}/>
</div>
)
}
onShow() {
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 = ""
// }
strClass = this.props.isActive ? 'active' : "";
return (
<div className={"content " + strClass}>
<h1>我是子元素 </h1>
</div>
)
}
}
ReactDOM.render(
<ParenetCom />, // 渲染父元素
document.querySelector('#root') //尋找文件對象
)
.content {
width: 400px;
height: 200px;
background-color: skyblue;
display: none;
}
.content.active{
display: block;
}