React Referenced组件未定义

时间:2018-05-17 12:45:24

标签: reactjs

我试图在组件树中传递一个值,我在组件上使用refs来做到这一点。 但是,React一直告诉我Cannot read property 'setState' of undefined。这意味着它无法找到对我的组件的引用,但事实并非如此:

<FormBox url = "api/skills" handleClose = {this.handleClose} ref = {(ref)=>{this.formbox = ref;}}/>

一旦容器的状态发生变化,我就会改变formbox的状态,如下所示:

componentDidUpdate(){
  this.formbox.setState({parent: this.state.parent});
}

我究竟做错了什么?我该怎么做才能解决这个问题?

编辑:以下是整个文件:

class ModalForm extends Component{

  constructor(props, context) {
    super(props, context);

    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);

    this.state = {
      show: false,
      parent: 0
    };

  }

  componentDidUpdate(){
    this.formbox.setState({parent: this.state.parent});
  }

  handleClose(event) {
    console.log("hiding");
    this.setState({ show: false });
  }

  handleShow(event) {
    console.log("showing");
    this.setState({ show: true });
  }

  render() {

    return (
      <div>

        <Modal show={this.state.show} onHide={this.handleClose}>
          <Modal.Header closeButton>
            <Modal.Title>Add A Skill</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <FormBox url = "api/skills" handleClose = {this.handleClose} ref = {(ref)=>{this.formbox = ref;}}/>
            </Modal.Body>
            <Modal.Footer>
                <Button onClick={this.handleClose}>Close</Button>
            </Modal.Footer>
        </Modal>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

你应该在构造函数中create the ref

constructor(props) {
  super(props, context);
  this.handleShow = this.handleShow.bind(this);
  this.handleClose = this.handleClose.bind(this);

  // Create ref instance
  this.formboxRef = React.createRef();

  this.state = {
    show: false,
    parent: 0
  };
}

然后将ref附加到渲染函数中的组件:

<FormBox url="api/skills" handleClose={this.handleClose} ref={this.formboxRef}/>

现在,您可以通过以下方式在组件上下文中的任何位置使用当前的ref:

componentDidUpdate(){
  this.formboxRef.current.setState({parent: this.state.parent});
}