Javascript 从另一个组件调用时将类名传递给子组件

Javascript 从另一个组件调用时将类名传递给子组件,javascript,reactjs,Javascript,Reactjs,在React with Gatsby中,我试图向layouts/index.js的子组件添加className。当onClick在另一个组件中注册时,如何在props中传递要与组件一起使用的类名 index.js class Template extends React.Component { constructor(props) { super(props) this.state = { navIsVisible: false, } this.han

在React with Gatsby中,我试图向
layouts/index.js
的子组件添加
className
。当
onClick
在另一个组件中注册时,如何在
props
中传递要与组件一起使用的类名

index.js

class Template extends React.Component {
constructor(props) {
    super(props)
    this.state = {
      navIsVisible: false,
    }
    this.handleNavIsVisible = this.handleNavIsVisible.bind(this)
  }

  handleNavIsVisible() {
    this.setState({
      navIsVisible: !this.state.navIsVisible
    })
  }
  render() {
  const { children } = this.props

    return (
      <div> 
        <MenuButton navIsVisible={this.handleNavIsVisible}/>
         <div className="page">
           ...
         </div>
         {/* Adding the class here seems to be the best option but does not activate onClick, yet does if adding to a div with Menu contained */}
         <Menu className={`${this.state.navIsVisible ? 'nav-is-visible' : ''}`}/>
      </div>
    )
  }
}

或者,在Menu.js中,但不确定如何将状态更改传递到此组件?

它在div上工作而不在菜单组件上工作的原因是,当您将其传递到div时,它会将该类“直接”添加到div HTML元素中,但当您将其传递到组件时,它只是将其作为道具传递。这实际上取决于您在菜单组件的渲染方法中执行的操作以及从中返回的内容。如果你确保抓取道具并将其附加到它渲染的任何东西上,它将像在div上一样工作

例如:

类菜单扩展组件{
渲染(){
返回(
菜单组件

) } }
它在div而不是菜单组件上工作的原因是,当您将其传递给div时,它会将该类“直接”添加到div HTML元素,但当您将其传递给组件时,它只是将其作为道具传递。这实际上取决于您在菜单组件的渲染方法中执行的操作以及从中返回的内容。如果你确保抓取道具并将其附加到它渲染的任何东西上,它将像在div上一样工作

例如:

类菜单扩展组件{
渲染(){
返回(
菜单组件

) } }
如果您所说的这些组件没有父子关系,或者关系非常高,那么您应该考虑使用新的React上下文API(它是native React的一部分,而不是npm包)。无论是那样还是重复都是一个不错的选择谢谢。我去看看。目前,我已将
className={'${this.state.navisible?'nav is visible':'}}}
添加到
div
中,然后更改我的CSS以适应操作。我希望你的建议能给我一个更好的方法来实现这个目标。想不出更好的方法了。这是我个人使用它的方式。但我不会用字符串文字来包装它。我只是用一个正规的三元数
className={this.state.navisible?'nav is visible':''}
如果您所说的这些组件没有父子关系或者关系非常高,您应该考虑使用新的React上下文API(它是本机React的一部分,而不是npm包)。无论是那样还是重复都是一个不错的选择谢谢。我去看看。目前,我已将
className={'${this.state.navisible?'nav is visible':'}}}
添加到
div
中,然后更改我的CSS以适应操作。我希望你的建议能给我一个更好的方法来实现这个目标。想不出更好的方法了。这是我个人使用它的方式。但我不会用字符串文字来包装它。我只是用一个正规的三元数<代码>类名={this.state.navisible?'nav可见':''}
class MenuButton extends Component {
  constructor(props) {
    super(props)
    this.menuClick = this.menuClick.bind(this)
  }

  menuClick(){
    this.props.navIsVisible();
  }

  render () {
     return (
        <div className="sticky-menu-button">
            <span onClick={this.menuClick}>Menu</span>
        </div>
    )
  }
}

MenuButton.propTypes = {
    navIsVisible: PropTypes.func,
}
class Menu extends Component {

render () {
  return (
    <div className={this.props.className}>
      <p> Menu Component </p>
    </div>
   )
 }
}