React Props(父传子)

学习目标

  • 了解prop概念
  • 了解父传子的原理
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') //寻找文件对象
)
  • test.css
.content {
    width: 400px;
    height: 200px;
    background-color: skyblue;
    display: none;
}
.content.active{
    display: block;
}

猜你喜欢

转载自blog.csdn.net/A_bad_horse/article/details/105560126