【问题标题】:Not able to call the the method of the child component in react无法在反应中调用子组件的方法
【发布时间】:2020-07-13 06:49:19
【问题描述】:

我有以下组件。

这个组件接受可以调用的函数的props。

deleteIcon = () => {
 console.log("deleting the document");
}

    export const Parent = (props) => {

      return (
         <button onclick={() => {deleteIcon()}}
      )

    }

现在,我有另一个使用该组件的组件。它有自己的 deleteIcon 方法实现。

deletechildIcon = () => {

}

export const child = () => {
     return (
   <Parent deleteIcon={() => {deletechildIcon()}} />
 )
}

所以,从子级开始,它仍然在调用父级方法,而不是子级。谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    一些注意点:

    • onClick 而不是onclick
    • 不需要在 props 内部使用箭头函数,这可能会导致性能损失,这不是最佳做法
    • 在组件中编写函数
    • Child 组件是在 Parent 内部调用的组件,您将其设置为相反的

    尝试文本演示:

    const Parent = () => {
      const deleteIcon = () => {
        console.log("deleting the document");
      };
      return <Child deleteIcon={deleteIcon} />;
    };
    
    const Child = props => {
      return <button onClick={props.deleteIcon}>XXX</button>;
    };
    
    ReactDOM.render(<Parent />, document.getElementById("root"));
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

    【讨论】:

    【解决方案2】:

    您在父组件中调用 deleteIcon 方法,而不是 props.deleteIcon

    【讨论】:

    • 是的,但问题是父母只能调用父母方法
    【解决方案3】:

    听起来您希望 Parent 有一个默认的 deleteIcon 属性,可以在特定实现中选择性地覆盖它。你可以通过编辑Parent 来做到这一点:

    deleteIcon = () => {
     console.log("deleting the document");
    }
    
    export const Parent = (props) => {
      const buttonOnClickHandler = props.deleteIcon || deleteIcon;
      return (
        <button onClick={() => {buttonOnClickHandler()}}
      )
    }
    

    或者你可以使用默认参数:

    deleteIconDefault = () => {
     console.log("deleting the document");
    }
    
    export const Parent = ({
      deleteIcon = deleteIconDefault
    }) => {;
      return (
          <button onClick={() => {this.props.deleteIcon()}}
      )
    }
    

    希望这会为您指明正确的方向!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 2021-01-31
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-10
      相关资源
      最近更新 更多