[英]React JS - Calling function passed as a prop
I am passing a function to handle the state of a modal window component from a parent component to a child component in a React app.我正在传递一个函数来处理模态窗口组件的状态,从父组件到 React 应用程序中的子组件。
Parent Component父组件
class App extends Component {
constructor() {
super();
this.state = {
'modalVisibility' : false,
'modalContent' : ""
}
this.handleModal = this.handleModal.bind(this);
}
handleModal(visibility, content, innerClass){
this.setState({
modalVisibility: visibility,
modalContent: content ? content : null,
modalClass: innerClass ? innerClass : null
});
}
render() {
return (
<div>
<Modal show={this.state.modalVisibility} content={this.state.modalContent} />
<Content modal={this.handleModal} />
</div>
)
}
}
Child Component子组件
class Content extends Component {
constructor(props) {
super(props);
console.log(this.props.modal); // Object { modal: handleModal() }
this.props.modal(true,"hello modal"); // TypeError: _this.props.modal is not a function
}
}
The function handleModal()
looks like it is successfully passed to the Content
component and seems to be defined as a function, but calling it throws an error.函数handleModal()
看起来像是成功传递给Content
组件,似乎被定义为一个函数,但是调用它会抛出错误。
What am I missing here?我在这里缺少什么?
Your constructor doesn't have props bound to this
.您的构造函数没有绑定到this
道具。 Use the props argument to access the props in the constructor function.使用 props 参数访问构造函数中的 props。
constructor(props) {
super(props);
console.log(props.modal);
props.modal(true, 'hello modal');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.