【发布时间】:2019-05-14 11:49:39
【问题描述】:
我最近开始使用 reactjs、typescript 和 Office UI Fabric。但我已经在为面料中的一种成分而苦苦挣扎。 在此示例中,我有一个简单的 Product 组件,其中包含一个 SpinButton 和一个 DefaultButton。 单击 DefaultButton 时,我想获取 SpinButton 的值并将焦点设置在它上面。 为了获得 ISpinButton 接口成员,我使用了 React.RefObject 的引用。 我的代码如下所示:
import * as React from 'react';
import { DefaultButton } from 'office-ui-fabric-react/lib/Button';
import { SpinButton } from 'office-ui-fabric-react/lib/SpinButton';
class Product extends React.Component<{}, {}> {
private spbStockRef: React.RefObject<SpinButton> = React.createRef<SpinButton>();
public render(): JSX.Element {
return (
<React.Fragment>
<SpinButton
ref={this.spbStockRef}
defaultValue="0"
label={'Stock '}
min={0}
max={99999}
step={1}
onFocus={() => console.log('onFocus called')}
onBlur={() => console.log('onBlur called')} />
<DefaultButton onClick={this.onButtonClick} />
</React.Fragment>)
}
private onButtonClick = (e: React.MouseEvent<HTMLButtonElement>) => {
const node = this.spbStockRef.current!;
if (node) {
console.log(node.value);
node.focus();
}
}
}
export default Product;
在 onButtonClick 内部,Visual Studio 的智能感知建议在节点变量上同时使用“value”和“focus()”,因此应该可以访问实际的 ISpinButton 成员。
但是当单击按钮时,console.log(node.value) 输出 undefined 并且在 node.focus() 上引发 TypeError: TypeError: node.focus 不是函数。 我还想提一下,console.log(node) 会输出一个正确的实例化对象,因此 ref 可以正常工作。
知道我在这里做错了什么吗? 在 SpinButton 组件的示例中,也没有任何内容指出如何进行这项工作。
https://developer.microsoft.com/en-us/fabric?example=#/components/spinbutton
谢谢
【问题讨论】:
标签: reactjs typescript office-ui-fabric