【问题标题】:Add/Remove class to child component div from parent component using refs使用 refs 从父组件向子组件 div 添加/删除类
【发布时间】:2020-06-02 04:19:04
【问题描述】:

我想通过单击侧边栏菜单按钮(在父组件中)从父组件添加/删除子组件的外部 div 类。 单击 SidNav 切换按钮,展开导航并将类添加到子组件的外部 div,以便内容被推送到右侧。

已尝试:将 ref 作为道具传递 - 我正在获取参考,但当从父组件应用类时,实际的子 dom 不会更新。

任何建议都会有所帮助。

片段:

父组件:

return(<Child ref={this.ref} navigation={navigation} searchParams={parsedQuery} />)

子组件:

function render() {
  const { navigation, classlg2, ref } = this.props;
  return (
    <div className="bx--grid page-content--wrapper">
      <div className="bx--row">
        <div
          ref={ref}
          className={
            navigation.length > 0
              ? "bx--col-lg-2 bx--col-lg-14"
              : "bx--col-lg-16"
          }
        >
          {routeComponentsElements}
        </div>
      </div>
    </div>
  );
}

bx--col-lg-2 是我需要在切换SideNav 时添加和删除的类。

如果使用状态来处理类名,那么内容会重新呈现。 示例:子组件中有 ajax 调用,当单击 menubutton 时,它会重新呈现页面返回其主页。

【问题讨论】:

  • 能否请您提供您的代码
  • 你能添加一个stackblitz示例或代码块吗
  • 我认为这是一个 XY 问题。为什么在这种情况下需要使用 refs?只需将布尔值“isExpanded”传递给孩子并有条件地应用样式类。

标签: reactjs ref


【解决方案1】:

做这样的事情。

父组件

this.state = {
  childClass: false
}

toggleChildClass = () => {
  this.setState(prevState =>({
    childClass: !prevstate.childClass
  }))
}

render(){
  const {childClass} = this.state;

  return(
    <>
        <button onClick={this.toggleChildClass}>Toggle Class</button>
        <ChildComponent childClass={childClass} />
    </>
  )
}

子组件

render(){ 
    const { childClass } = this.props;
    return(
        <div 
            className={childClass ? "bx--col-lg-2 bx--col-lg-14" 
                                  : 'bx--col-lg-16'}> 
          {routeComponentsElements} 
        </div>
     )
 }

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 2018-09-15
    • 1970-01-01
    • 2018-07-22
    • 2018-07-04
    • 2016-12-08
    • 2018-06-26
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多