ReactJS-从另一个组件更改组件的类?

时间:2019-03-07 16:14:29

标签: javascript reactjs

React非常新,来自jQuery背景,我想做的第一件事就是切换类。

我了解如何在类似的react组件中切换类:

class ButtonParent extends React.Component {
  constructor(props) {    
    super(props)
    this.state = {
      condition: false
    }
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick() {
    this.setState({
      condition: !this.state.condition
    })
  }
  render() {
    return (
      <ButtonChild        
        className={ this.state.condition ? "button toggled" : "button" }
        toggleClassName={ this.handleClick }
      >
        Click me if you dare!
      </ButtonChild>
    )
  }
}

class ButtonChild extends React.Component {
  render() {
    return (
      <div
        className={ this.props.className }
        onClick={ this.props.toggleClassName }
      >
        { this.props.children }
      </div>
    )    
  }
}

ReactDOM.render(<ButtonParent />, document.getElementById('app'))

但是如果我要使用一个单独的组件来切换该组件的类怎么办?在React中没有简单的方法可以做到这一点吗?

谢谢!

1 个答案:

答案 0 :(得分:-2)

只需在ButtonParent.js文件附近创建一个ButtonChild.js文件,然后导出您的组件

export default class ButtonChild extends React.Component {
  render() {
    return (
      <div
        className={ this.props.className }
        onClick={ this.props.toggleClassName }
      >
        { this.props.children }
      </div>
    )    
  }
}

将其导入到您的ButtonParent.js文件中

import ButtonChild from './ButtonParent.js'
相关问题