我可以更改位于React组件中的div的不透明度状态吗?

时间:2018-07-26 16:29:31

标签: javascript reactjs components containers

我正在尝试将组件代码和容器代码分开。

我知道Main.js中的按钮“隐藏”被按下时会调用MainContainer中的函数handleHide(),因为位于Alert函数中的handleHide()起作用了。

所以基本上,这是不透明性无法通过props更改或我丢失了一些东西的问题。

  

下面是我的Main.js文件(组件)

import React from 'react'

const styles = {
  transition: 'all 1s ease-out'
}

export class Main extends React.Component {
  render () {
    return (
      <div>
        <nav>
          <div className='nav-wrapper'>
            <a href='/' className='brand-logo'>Todays&rsquo; EDM</a>
            <ul id='nav-mobile' className='right hide-on-med-and-down'>
              <li><a href='sass.html'>Music</a></li>
              <li><a href='badges.html'>Playlists</a></li>
              <li><a href='collapsible.html'>News</a></li>
            </ul>
          </div>
        </nav>

        <div className='container'>
          <div className='row'>
            <div className='s12' />
          </div>

          <div className='row'>
            <div className='s8 offset-s2 center-align'>
              <div className='card green accent-4 z-depth-2'
                style={{...styles, opacity: this.props.opacity, transform: 'scale(' + this.props.scale + ')'}}>
                <div className='card-content white-text'>
                  <span className='card-title'>Title</span>
                </div>

                <div className='card-action'>
                  <a onClick={this.props.hide}>HIDE</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }
}
  

这是我的MainContainer.js文件(容器)

import React from 'react'
import { Main } from '../components/Main'

export class MainContainer extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      opacity: 1,
      scale: 1
    }

    this.handleHide = this.handleHide.bind(this)
    this.handleScale = this.handleScale.bind(this)
  }

  handleHide () {
    this.setState({
      opacity: 0
    })
    alert('Goodbye world')
  }

  handleScale () {
    this.setState({
      scale: this.state.scale > 1 ? 1 : 1.2
    })
  }

  render () {
    let hide = this.handleHide
    return (
      <Main hide={hide} />
    )
  }
}

1 个答案:

答案 0 :(得分:2)

如下所示在MainContainer.js中修改您的代码...

<Main hide={hide} {...this.state} />