【问题标题】:React - interact with child componentReact - 与子组件交互
【发布时间】:2017-06-30 00:38:46
【问题描述】:

我想知道什么是父子组件交互的最佳实践,以及以下方法是否满足良好实践。

假设我们有两个组件:ParentChild,其中 Parent 以类似于获取元素 ref 的方式获取 Child 的处理程序。

class Parent extends React.Component<{}, {}> {

  private handlers: {
    Child: ChildHandlers
    /** And so on... **/
  };

  render() {
    return (
      <div>
        <Child handlers={(handlers: ChildHandlers) => { this.handlers.Child = handlers; }} />
        <button onClick={() => this.handlers.Child.toggle() /** Or change Parent.state and then trigger **/}>toggle from parent</button>
      </div>
    );
  }
}

class Child extends React.Component<ChildProps, ChildState> {
  constructor(props: ChildProps) {
    super(props);

    this.exposeHandlers();
  }

  private toggle(): void {
    this.setState({ visible: !this.state.visible });
  }

  private exposeHandlers() {
    let handlers: ChildHandlers = {
      toggle: () => this.toggle()
    };

    this.props.handlers(handlers);
  }

  render() {
    return (
      <div>
        { this.state.visible && (
          <div>
            <h2>I'm being toggled!</h2>
            <button onClick={() => this.toggle()} />toggle from child<button>
          </div>
        ) }
      </div>
    );
  }
}

这似乎很好,因为:

  • 允许保持一致
  • 这就像是暴露了两个组件都使用的接口,而没有过多地耦合它们
  • 在合理的范围内将 Child 的状态排除在 Parent 的业务之外
  • 在更新 Child 的状态后,向 toggle 方法添加回调以在 Parent 上执行一些操作会更容易。

但由于我没有经验,这有什么(甚至是最轻微的)问题吗?

【问题讨论】:

    标签: reactjs oop typescript encapsulation


    【解决方案1】:

    对我来说似乎有点矫枉过正。

    公开这些方法并仅在Parent 中引用Child 的实例然后在需要时调用这些方法有什么问题?

    家长:

    class Parent extends React.Component<{}, {}> {
        private child: Child;
    
        render() {
            return (
                <div>
                <Child ref={ el => this.child = el } />
                <button onClick={() => this.child.toggle()}>toggle from parent</button>
                </div>
            );
        }
    }
    

    孩子:

    class Child extends React.Component<{}, ChildState> {
        public toggle(): void {
            this.setState({ visible: !this.state.visible });
        }
    
        render() {
            if (!this.state.visible) {
                return <div />;
            }
    
            return (
                <div>
                    <div>
                        <h2>I'm being toggled!</h2>
                        <button onClick={() => this.toggle()}>toggle from child</button>
                    </div>
                </div>
            );
        }
    }
    

    【讨论】:

    • 这绝对是矫枉过正 - 不知道直接访问 Child 的能力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 2018-03-19
    • 2014-12-04
    • 2017-07-18
    相关资源
    最近更新 更多