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

React JS-作为属性传递的调用函数

  •  0
  • yevg  · 技术社区  · 6 年前

    我正在传递一个函数来处理模式窗口组件的状态,从父组件到React应用程序中的子组件。

    父组件

    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>
            )
        }
    }
    

    子组件

    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 
        }
    }
    

    函数 handleModal() 似乎它已成功传递到 Content 组件,似乎被定义为一个函数,但是调用它会抛出一个错误。

    我这里缺什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Matt Greenberg    6 年前

    构造函数没有绑定到的属性 this . 只需使用props参数访问构造函数函数中的props。

    conscturctor(props){
       super(props);
       console.log(props.modal);
       props.modal(true, 'hello modal');
    

    }