无法在反应中调用子组件的方法

我有以下组件。


该组件接受可以调用的函数的道具。


deleteIcon = () => {

 console.log("deleting the document");

}


    export const Parent = (props) => {


      return (

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

      )


    }

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


deletechildIcon = () => {


}


export const child = () => {

     return (

   <Parent deleteIcon={() => {deletechildIcon()}} />

 )

}

所以,从孩子仍然是调用父方法而不是子方法。谁能帮我这个 ?


幕布斯7119047
浏览 103回答 3
3回答

largeQ

听起来您想要一个可以在特定实现中选择性覆盖Parent的默认道具。deleteIcon你可以通过这样的编辑来做到这Parent一点:deleteIcon = () => {&nbsp;console.log("deleting the document");}export const Parent = (props) => {&nbsp; const buttonOnClickHandler = props.deleteIcon || deleteIcon;&nbsp; return (&nbsp; &nbsp; <button onClick={() => {buttonOnClickHandler()}}&nbsp; )}或者您可以使用默认参数:deleteIconDefault = () => {&nbsp;console.log("deleting the document");}export const Parent = ({&nbsp; deleteIcon = deleteIconDefault}) => {;&nbsp; return (&nbsp; &nbsp; &nbsp; <button onClick={() => {this.props.deleteIcon()}}&nbsp; )}希望这会为您指明正确的方向!

qq_花开花谢_0

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

白板的微信

一些注意点:onClick而不是onclick不需要在 props 中使用箭头函数,这可能会导致性能损失,这不是最佳实践在组件中编写函数Child组件是在内部调用的组件Parent,您将其设置为相反的尝试文本演示:const Parent = () => {&nbsp; const deleteIcon = () => {&nbsp; &nbsp; console.log("deleting the document");&nbsp; };&nbsp; return <Child deleteIcon={deleteIcon} />;};const Child = props => {&nbsp; 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>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript