【问题标题】:`ref` issue with react-bootstrap elementsreact-bootstrap 元素的“ref”问题
【发布时间】:2015-07-08 08:44:23
【问题描述】:

我正在尝试使用 ref='roleType' 获取由 DropdownButton 选择的 get 值,但无论我尝试什么都失败了。

    <DropdownButton ref='roleType' bsStyle='link' title='Role' key='1'  bsSize='xsmall'>
      {_items}
    </DropdownButton>

我尝试了以下方法:

 React.findDOMNode(this.refs.roleType)
 this.refs.roleType.getDOMNode()

注意:我不确定它是否重要。 DropdownButton 位于 Panel 内,而 section 位于 div 内。

【问题讨论】:

  • 我猜你将一个函数传递给onSelect 并从那里获取值。
  • @FelixKling 但为什么不使用ref
  • 因为看起来您无法通过 ref 访问该值。

标签: javascript twitter-bootstrap reactjs react-bootstrap


【解决方案1】:

您应该使用DropdownButtononSelect 属性,如docs 中所述。

var DropdownButton = ReactBootstrap.DropdownButton;
var MenuItem = ReactBootstrap.MenuItem;

var Hello = React.createClass ({
    getInitialState() { 
        return { key: null }
    },

    onSelect(key) {
        this.setState({ key: key });
    },

    render() {
        var selected = this.state.key ? <p>Selected: {this.state.key}</p> : '';
        return (<div>
        <DropdownButton bsStyle="primary" title="Test" onSelect={this.onSelect}>
          <MenuItem eventKey='1' active={this.state.key==='1'}>Action</MenuItem>
          <MenuItem eventKey='2' active={this.state.key==='2'}>Another action</MenuItem>
          <MenuItem eventKey='3' active={this.state.key==='3'}>Active Item</MenuItem>
          <MenuItem divider />
          <MenuItem eventKey='4' active={this.state.key==='4'}>Separated link</MenuItem>
        </DropdownButton>
        {selected}
        </div>);
    }
});

React.render(<Hello/>, document.getElementById('container'));

这是一个有效的小提琴:

https://jsfiddle.net/gadr/azm159g4/2/

【讨论】:

  • 但为什么不使用ref
  • ref 在您需要从并非发起事件的事物中获取价值时很有用。在这种情况下,真的没有任何意义。另外,好像是not entirely possible通过refs进行交互。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 2016-01-19
相关资源
最近更新 更多