{ this.s-6ren">
gpt4 book ai didi

javascript - 将函数传递给 React Component 然后调用它会导致 "Uncaught TypeError: x is not a function"

转载 作者:行者123 更新时间:2023-12-02 20:50:49 25 4
gpt4 key购买 nike

我试图在 React 中显示 Modal ,一旦调用 onClose ,它应该自行关闭。我有一个名为 showModal() 的函数:

  showModal = () => {
this.setState(prev=>({
modalOpen: !prev.modalOpen
}));
};

我将它绑定(bind)在构造函数中:

  constructor(props) {
super(props);
this.state = {
...
modalOpen: false,
};
this.showModal = this.showModal.bind(this);
}

在某些时候,我正在调用我的 Modal 组件:

function = () => {
...
return (
<div {...attrs}>
...
<div>
<DocumentModal onClose={this.showModal} show={this.state.modalOpen} document = {documents[0].id} />
<button onClick={() => {this.showModal()}}>{click me} &raquo;</button>
</div>
}
</div>
</div>
);
}

这是Modal组件:

class DocumentModal extends React.Component {
constructor(props) {
super(props);
this.state = {
id: this.props.document,
};
}

...

render() {
const modalStyles = {
modal: {
minWidth: '400px',
padding: '2rem',
}
};

if (!this.props.show) {
return null;
}

return (
<div>
<Modal open={this.props.show} little showCloseIcon={true} styles={modalStyles}>
<div className="item">
...
<button type="button" className="close" aria-label="Close"
onClick={() => {this.props.onClose()}}/>
</div>
</Modal>
</div>
);
}
}

Modal.propTypes = {
onClose: PropTypes.func.isRequired,
show: PropTypes.bool,
document: PropTypes.string,
};

export default DocumentModal;

当点击Modal内的close按钮时,我收到以下错误:

Uncaught TypeError: n.props.onClose is not a function
at n.onClickCloseIcon (modal.js:66)
at Object.c (react-dom.production.min.js:26)
at Object.invokeGuardedCallback (react-dom.production.min.js:25)
at Object.invokeGuardedCallbackAndCatchFirstError (react-dom.production.min.js:25)
at p (react-dom.production.min.js:30)
at b (react-dom.production.min.js:32)
at y (react-dom.production.min.js:32)
at Array.forEach (<anonymous>)
at v (react-dom.production.min.js:31)
at S (react-dom.production.min.js:34)

可能值得一提的是,有多个项目会呈现Modal。例如,5 个不同的项目具有 5 个不同的 ID,但 onClose 方法对每个人来说仍然相同。

我做错了什么?

最佳答案

您必须在 Modal 组件中添加 onClose

<Modal open={this.props.show} little showCloseIcon={true} styles={modalStyles} onClose={this.props.onModalClose}> //rename your prop function to onModalClose//

关于javascript - 将函数传递给 React Component 然后调用它会导致 "Uncaught TypeError: x is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61610661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com