问题描述
在我的 React 应用程序中,我使用 react-fluent-ui 来处理很多样式。在基于类的组件的一个块中,我使用 TextField
作为过滤器元素。我还在 clear
中包含了一个 TextField
图标,以便用户可以单击它来清除输入字段中的文本。我遇到的问题是如何在图标所在的代码块中包含对函数的引用。请注意,onClick
需要专门位于图标上,而不是位于 TextField
上。这是代码块:
<TextField
label="ID:"
defaultValue={this.props.filters.id}
onChange={this.onFilterById}
styles={{ root: { maxWidth: 300 } }}
borderless
underlined
iconProps={ clearIconProps }
/>
上面引用的 iconProps
如下所示:
const clearIconProps = {
iconName: 'clear',cursor: 'pointer',}
当我尝试使用粗箭头语法将函数添加到 clearIconProps
时,像这样,出现语法错误:(解析错误:意外标记):
const clearIconProps = {
onClick={() => clearFilter()},iconName: 'clear',}
我也试过这个,但它也导致了语法错误:(解析错误:意外标记):
const clearIconProps = {
onClick={clearFilter},}
为了记录,目前,clearFilter()
看起来像这样:
const clearFilter = () => {
// Add code to clear field
console.log('clearFilter() was triggered...');
}
解决方法
按照@NiceToMeetYou 的建议,这段代码是错误的:
const clearIconProps = {
onClick={clearFilter},// This has to be corrected to onClick: clearFilter,iconName: 'clear',cursor: 'pointer',}
现在变成了这样:
const clearIconProps = {
onClick: clearFilter,}
我们将不得不做这样的事情,以实现 => Note,the onClick needs to be on the icon specifically,not on the TextField. This is the block of code:
class TextFieldBasicExample extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
const node = ReactDOM.findDOMNode(this);
if (node instanceof HTMLElement) {
const child = node.querySelector('i');
child.addEventListener('click',() => console.log("Hello world"))
console.log("I am here",child)
}
}
render() {
return (
<Stack horizontal tokens={stackTokens} styles={stackStyles}>
<Stack {...columnProps}>
<TextField label="With an icons" iconProps={iconProps} />
</Stack>
</Stack>
);
}
}
这是相同的完整代码: codepen
,Fluent UI 不支持来自 TextField 图标的点击事件。您应该手动创建一个函数... 尝试执行以下操作。
class YourComponent ... {
constructor() {
this.unifiedTextFieldId = xxx; // init textfield id
...
}
componentDidMount() {
const textField = document.getElementById(this.unifiedTextFieldId);
if(textField) {
const inputEle = textField.getElementsByTagName('input')[0];
inputEle.parentNode.childNodes[1].addEventListener('click',clearFilter);
}
}
...
render() {
return (
...
<TextField
id = {this.unifiedTextFieldId}
label="ID:"
defaultValue={this.props.filters.id}
onChange={this.onFilterById}
styles={{ root: { maxWidth: 300 } }}
borderless
underlined
iconProps={ clearIconProps }
/>
...