我有两个部分:

class ParentComponent extends Component {
  toggleChildMenu() {
    ?????????
  }
  render() {
    return (
      <div>
        <button onClick={toggleChildMenu.bind(this)}>
          Toggle Menu from Parent
        </button>
        <ChildComponent />
      </div>
    );
  }
}

Child Component:

class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu() {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}

我需要从父组件更改子组件的open状态,或者在单击父组件中的按钮时从父组件调用子组件的toggleMenu()

推荐答案

应该在父组件中管理状态.可以通过添加属性将open值传递给子组件.

class ParentComponent extends Component {
   constructor(props) {
      super(props);
      this.state = {
        open: false
      };

      this.toggleChildMenu = this.toggleChildMenu.bind(this);
   }

   toggleChildMenu() {
      this.setState(state => ({
        open: !state.open
      }));
   }

   render() {
      return (
         <div>
           <button onClick={this.toggleChildMenu}>
              Toggle Menu from Parent
           </button>
           <ChildComponent open={this.state.open} />
         </div>
       );
    }
}

class ChildComponent extends Component {
    render() {
      return (
         <Drawer open={this.props.open}/>
      );
    }
}

Reactjs相关问答推荐

Npm运行构建`在Next.js 14中不起作用

无法从正在使用Reaction的Electron 商务store 项目中的购物车中删除项目

REACTJS:在Reaction中根据路由路径更改加载器API URL

如何在单击行中的图标时避免选中ionic 复选框?

捕获表单数据时的Reactjs问题

react 挂钩-使用有效澄清

在Reaction中管理多个状态

无法使用Reaction日期选取器和Next.js设置初始日期

修改React数据表扩展组件

如何更新redux状态存在的输入框

useState数组不更新

如何根据用户在react.js中的 Select , Select 多个心形图标?

未处理的拒绝 (TypeError):无法读取未定义的属性(读取协议)

在按钮单击中将动态参数传递给 React Query

改变输入的默认值时出现问题:number react-hook-form

我应该使用 useEffect 来为 React Native Reanimated 的 prop 值变化设置动画吗?

如何从 React Redux store 中删除特定项目?

网格项不缩小以适应包含的可滚动列表

如何将 id 从页面传递到另一个页面?

如何将本地视频文件上传到 Google Cloud