react--button组件控制其他组件显示和隐藏1

想要达到的目的和结果: 用子组件的button按钮控制其他子组件的显示和隐藏

1.创建子组件的js(MyButton.js)和less (MyButton.less)

import React, { Component } from 'react'
import './MyButton.less'
import PropTypes from 'prop-types'

class MyButton extends Component {
//对Component设置propTypes属性,可以为Component的props属性进行类型检查。
  static propTypes = {
    getChildrenMsg: PropTypes.func
  }
//可以获取到父组件传下来的参数。只要组件存在constructor,就必要要写super,否则this指向会错误。
  constructor (props) {
    super(props)
    this.state = {
      isShow: true,
      color: '#071023'
    }
  }
//可以控制显示和隐藏、点击有变化的方法
  toParent = () => {
    const { isShow, color } = this.state
    if (color === '#071023') {
      this.setState({
        color: '#f8dc3e',
        isShow: !isShow
      }, () => {
        this.props.getChildrenMsg(this.state.isShow)
      })
    } else if (color === '#f8dc3e') {
      this.setState({
        color: '#071023',
        isShow: !isShow
      }, () => {
        this.props.getChildrenMsg(this.state.isShow)
      })
    }
  }
  render () {
    return (
      
) } } export default MyButton
.Button{
    width: 54px;
    height: 54px;
    background-image: url('../../../assets/images/mybutton/mybutton.png');
    border: none;
    background-repeat: no-repeat;
    float: left;
    margin-right: 30px;
//是鼠标放到按钮上,箭头可以变成小手
    cursor: pointer;
}

2.在所需要控制的子组件的js里写

export default class OnlineTotal extends React.Component {  
static propTypes = {
    isShow: PropTypes.string
  }
 state={
    isHidden: 'block'
  }
/**
   * 参数变更触发的周期钩子
   */
  componentWillReceiveProps = (nextProps) => {
    if (nextProps.isShow !== this.isShow) {
      this.isShow = nextProps.isShow
      const { isHidden } = this.state
      this.setState({
        isHidden: (this.isShow === 'false' ? 'none' : 'block')
      }, () => {
        console.log("isHidden", isHidden)
      })
    }
  }

render () {
    const { isHidden } = this.state
    return (
      
内容.......
) } }

3.在index.js(父组件)

export default class Scee extends React.Component {
  /**
   * 初始化state
   */
  state = { isShow: 'true' }


  getChildrenMsg = (isShow) => {
    this.setState({
      isShow: isShow === true ? "true" : "false"
    })
  }

render () {
    const { isShow } = this.state
    return
        
} }

自己的总结,当然还有更好地方法,欢迎一起研究

你可能感兴趣的:(react,react,+,js)