0

我正在尝试在 Office UI Fabric React 基本列表的每一行上做一个按钮。该按钮将基本上调用具有项目 ID 的函数。代码是这样的

<List
  items = {this.state.relatedQuestions}
   onRenderCell = {this._onRenderListCell}
/>
private _onRenderListCell(relatedQuestion: IRelatedQuestion, index:number | undefined): JSX.Element {
   return (
      <div>
         <IconButton iconProps={deleteIcon} title="Remove" onClick={() => {this._removeRelatedQuestion(relatedQuestion.Id);}} /> 
         <Text>
            { relatedQuestion.Question }
         </Text>
      </div>
   );
}
private _removeRelatedQuestion(itemId: number) {
   alert(`Item id ${itemId}`);
   // actual code will be written later
}

但是单击图标按钮时,我不断收到以下错误。

Uncaught TypeError: Cannot read property '_removeRelatedQuestion' of undefined
    at Object.onClick (Faq.tsx:600)
    at BaseButton._this._onClick (BaseButton.js:191)
    at HTMLUnknownElement.callCallback (react-dom.development.js:336)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:385)
    at invokeGuardedCallback (react-dom.development.js:440)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:454)
    at executeDispatch (react-dom.development.js:584)
    at executeDispatchesInOrder (react-dom.development.js:609)
    at executeDispatchesAndRelease (react-dom.development.js:713)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:722)

如何将基本列表每一行中的按钮绑定到函数?

4

1 回答 1

0

在 cunstructor 中绑定您的函数或使用和 arow 函数作为处理程序:

constructor(props) {
  super(props);
  this.handleChange = this.handleChange.bind(this);
}
handleChange = () => {
  // call this function from render 
  // and this.whatever in here works fine.
};
于 2020-03-12T08:02:07.003 回答