从下拉办公室面料ui获取selectedKey

问题描述 投票:0回答:1

我创建了两个反应类。其中一个 - 子类名称 - ChildView,将数据绑定到dropdown office fabric组件,我在ParentView类上使用

ChildView,代码:

export class ChildView extends React.Component<any, IChildView >{
constructor(props) {
    super(props)

    this.state = {
        selectedKey: "1",
  selectedText: "one - 1",
        items: this._getItems()
    }

}
componentDidMount() {
    console.log('component did mount');
}
private _getItems() {
    return [
        { key: '1', text: 'one - 1' },
        { key: '2', text: 'two - 2' },
        { key: '3', text: 'three - 3' },
        { key: '4', text: 'four - 4' },
        { key: '5', text: 'five - 5' },
        { key: '6', text: 'six - 6' },
        { key: '7', text: 'seven - 7' },
        { key: '8', text: 'eight - 8' },
        { key: '9', text: 'nine - 9' },
        { key: '10', text: 'ten - 10' },
    ]
}

public render() {
    return (<Dropdown defaultSelectedKey={this.state.selectedKey}
        options={this.state.items} />);
}
}

ParentView,代码:

export default class ParentView extends React.Component<any, IParentView> {

constructor(props) {
    super(props);
}
public render(): React.ReactElement<IParentViewProps> {
    return (<ChildView />);}}

我的问题:

1)如何从子视图中返回选择父视图类中的键。?我在文档中读到,有'componentRef'。所以我在ParentView中更新我的代码:

public render(): React.ReactElement<IParentViewProps> {
    return (<ChildView componentRef={(ddItems)=>this.something = ddItems}/>);}}

我不知道接下来会发生什么。

reactjs dropdown spfx office-fabric
1个回答
1
投票

您可以从Parent传递一个函数到Child,当更改Child中的选定键时将调用该函数:

export class ChildView extends React.Component<any, IChildView >{
  constructor(props) {
    super(props)

    this.state = {
      selectedKey: "1",
      selectedText: "one - 1",
      items: this._getItems()
    }
    this.keyChanged = this.keyChanged.bind(this);
  }

  private _getItems() {
   return [...]
  }

  keyChanged(option){
    this.props.updateKey(option.key);
  }

 public render() {
  return (<Dropdown defaultSelectedKey={this.state.selectedKey}
    options={this.state.items}
    onChanged={this.keyChanged} />);
 }
}

和父渲染方法:

public render(): React.ReactElement<IParentViewProps> {
  return (<ChildView updateKey={this.setKey} />);
}

并定义setKey函数以接受父级中的键。

© www.soinside.com 2019 - 2024. All rights reserved.