代码之家  ›  专栏  ›  技术社区  ›  Matt

Typescript+React从子组件调用父方法

  •  0
  • Matt  · 技术社区  · 7 年前

    我试图从子组件调用父方法,但它不起作用,并且父元素中的方法未被触发。在这个例子中,我只有两个组件,其中 ChildHello 在中调用方法 Hello 组成部分。

    codesandbox

    import * as React from "react";
    
    interface Props {
      itemClicked: () => void;
    }
    
    export class Hello extends React.Component<Props, {}> {
      constructor(props: Props) {
        super(props);
      }
    
      itemClicked = val => {
        console.log(val);
      };
    
      render() {
        const { name } = this.props;
        return <h1 itemClicked={this.itemClicked}>{this.props.children}</h1>;
      }
    }
    
    const styles = {
      height: "400px"
    };
    
    export class ChildHello extends React.Component<Props, {}> {
      constructor(props: Props) {
        super(props);
      }
    
      render() {
        return (
          <div onClick={this.props.itemClicked} style={styles}>
            <Hello>Hello Child</Hello>
          </div>
        );
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Just code    7 年前

    你需要了解亲子关系 在childHello中,您使用的是单击事件。

     <div onClick={this.props.itemClicked} style={styles}>
            <Hello>Hello Child</Hello>
          </div>
    

    childhello由index.jsx页面调用

     <div style={styles}>
        <ChildHello name="CodeSandbox" />
      </div>
    

    这里没有传递任何单击事件。另外,hello组件位于错误的子组件内部。

    所有父组件都应该包含click方法,并且该方法应该作为道具传递。

    这样地

    起源:

    <div style={styles}>
        <Hello name="CodeSandbox" />
      </div>
    

    你好组件

    render() {
        const { name } = this.props;
        return <ChildHello itemClicked={this.itemClicked} />;
      }
    

    孩子你好

      render() {
        return (
          <div onClick={this.props.itemClicked} style={styles}>
            Hello
          </div>
        );
      }
    

    Sandbox demo