0

我在我的项目中使用 React Material-UI。我在渲染方法中放置了许多组件。然后奇怪的事情发生了。'this.refs.REFNAME' 不能引用某些组件。然后我检查了“this.refs”对象,如下图所示:

在此处输入图像描述

如您所见,第一行仅显示了一些可以引用的组件。我不明白为什么。谁能给我解释一下?非常感谢。

更新:感谢詹姆斯,我知道第一行应该是那个时候“this.refs”的状态。但是,为什么有些组件不在 refs 对象中?

这是代码的相关部分:

  render(){
    return <div>
      <Table ref='fromform'>
        <TableHeader>
          <TableRow>
            <TableHeaderColumn tooltip='The ID'>No.</TableHeaderColumn>
            <TableHeaderColumn tooltip='The Name'>Name</TableHeaderColumn>
            <TableHeaderColumn tooltip='The Status'>Notes</TableHeaderColumn>
          </TableRow>
        </TableHeader>
        <TableBody ref='fromformb'>
          {playerList.map(function(player, index){
              return <TableRow onTouchTap={this._onShowInfo.bind(this, index)} key={'row' + index}>
                <TableRowColumn>{index + 1}</TableRowColumn>
                <TableRowColumn>{player.name}</TableRowColumn>
                <TableRowColumn>{player.notes}</TableRowColumn>
              </TableRow>;
          }.bind(this))}
        </TableBody>
      </Table>
      <Dialog
        title='Player Info'
        ref='playerInfoDialog'>
        <form role='form' ref='fromfo'>
          <div className='form-group' ref='frowwmformb'>
            <TextField type='text' hintText='Player Name' ref='txtName' fullWidth={true} />
            <TextField type='text' hintText='Notes' ref='txtNotes' fullWidth={true} />
          </div>
        </form>
      </Dialog>
      <MainButtonGroup page='players' />
      <Spinner />
    </div>;
  }
  
  _onShowInfo(index){
    var player = playerList[index];
    console.log(this.refs);
    this.refs.playerInfoDialog.show();
    this.refs.txtName.setValue(player.name);
    this.refs.txtNotes.setValue(player.notes);
  }
}

我想用这段代码做的是在一个带有播放器列表的表中生成行,当我点击一行时,会显示一个包含该行数据的对话框。

但是不能引用引用为“txtName”和“txtNotes”的两个“TextField”(如最后两行,产生错误)。上图由 '_onShowInfo' 方法中的 'console.log' 生成。我添加了一些带有随机名称的 'ref' 只是为了测试。

4

2 回答 2

0

发生这种情况是因为当对话框被隐藏时,它的子级还没有挂载。因此,子项中定义的 refs 尚未设置。

但是,您可以在控制台中看到它们,因为 Chrome 在设置时会自动更新它,因为旧版本this.refs和新版本之间存在引用相等性。如果您想在给定的时间点记录 refs 并确保 Chrome 没有更新它,您可以这样做:console.log({ ...this.refs })

另一种方法是在组件的状态下保存对选定播放器的引用。然后你会有:

_onShowInfo(tid){
    var player = playerList[index];
    this.setState({selectedPlayer: player});
}

<Dialog
  title='Player Info'
  open={ !!this.state.selectedPlayer }
>
  <form role='form'>
    <div className='form-group'>
      <TextField type='text' hintText='Player Name' defaultValue={ this.state.player.name} fullWidth={true} />
    </div>
  </form>
</Dialog>
于 2016-03-31T14:02:14.907 回答
0

我找到了解决方案。更改 _onShowInfo 如下:

_onShowInfo(tid){
  var player = playerList[index];
  this.refs.playerInfoDialog.show();
  setTimeout(function(){
    console.log(this.refs);
    this.refs.name.setValue(player.name);
    this.refs.notes.setValue(player.notes);
  }.bind(this), 0);
}

但我不知道为什么。

于 2015-10-29T13:40:26.407 回答