react - 引用作为提示传递的组件

时间:2018-04-21 17:56:27

标签: reactjs react-props react-component

我在Test组件中渲染了EditModal组件。我通过' this.edit'来引用它。 我将UserForm组件作为提示传递给EditModal。我也试着引用它。但是' this.form'返回undefined。

为什么呢?有什么方法可以解决这个问题吗?

class Test extends React.Component {

   test(){
     this.form.someMethod();
   }

    render() {   
      return (
        <div>            
          <EditModal form={<UserForm ref={(form) => { this.form = form; }} />} ref={(edit) => { this.edit = edit; }}/>                        
        </div>
      );
    }
  }
export default Test;

// EditModal.js

class EditModal extends React.Component {
    constructor() {
        super();
        this.handleShow = this.handleShow.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.state = { show: false};
    }

    handleClose() {
        this.setState({ show: false });
    }

    handleShow(id) {
        this.setState({ show: true, currentId: id});
    }

  render() {
    return (
        <Modal show={this.state.show} onHide={this.handleClose}>
            <Modal.Header closeButton={false}>
            <Modal.Title>Uprav zaznam</Modal.Title>
            </Modal.Header>
        <Modal.Body>
           {this.props.form}
        </Modal.Body>
            <Modal.Footer>
            <Button onClick={this.handleClose}>Zatvorit</Button>
            </Modal.Footer>
      </Modal>
    );
  }
}

export default EditModal;

1 个答案:

答案 0 :(得分:0)

安装this.form组件后可以访问

UserForm(可能在EditModal内),并且仅当EditModal没有克隆表单支持并覆盖ref

因此,如果this.form未定义,则尚未安装,或者已卸载(通过调用时间测试方法)或ref已被覆盖。

如果没有EditModal的代码,任何人都无法确定上述情况中的哪一个。

相关问题