简体   繁体   English

泛化函数以重用不同的元素

[英]Generalizing function to reuse with different elements

How can I generalize these two functions to use in identical divs?如何概括这两个函数以在相同的 div 中使用?

showNotifyText = () => {
 const { showNotifyText } = this.state;
 this.setState({ showNotifyText: !showNotifyText });
};
showRoutineAvailabilityText = () => {
 const { showRoutineAvailabilityText } = this.state;
 this.setState({ showRoutineAvailabilityText: !showRoutineAvailabilityText });
};

Using this.state in setState is antipattern because setState is asynchronous .setState使用this.state是反模式,因为setState是异步的 If new state derives from previous one, setState function should be used.如果新状态从前一个派生而来,则应使用setState函数。

It could be either generalized method:它可以是通用方法:

toggleStateProperty = key => {
  this.setState(state => ({ [key]: !state[key] }));
};

Or higher-order function:或高阶函数:

toggleStatePropertyFactory = key => function () {
  this.setState(state => ({ [key]: !state[key] }));
};

...

toggleShowNotifyText  = toggleStatePropertyFactory('showNotifyText');

toggleRoutineAvailabilityText = toggleStatePropertyFactory('showRoutineAvailabilityText');

In case the method is supposed to be passed as a callback, the second option is preferable because it already binds the method to specific key:如果该方法应该作为回调传递,则第二个选项更可取,因为它已经将方法绑定到特定键:

<div onclick={this.toggleShowNotifyText}/>

vs对比

<div onclick={() => this.toggleStateProperty('showNotifyText')}/>

To generalize the method you could try adding the state key in the template as data, then read it inside the event handler:要概括该方法,您可以尝试在模板中添加状态键作为数据,然后在事件处理程序中读取它:

onClick = (event) => {
  const key = event.target.dataset.key;
  const value = this.state[key];
  this.setState({ [key]: !value });
}

render() {
  return (
    <div>
      <div onClick={this.onClick} data-key="showRoutineAvailabilityText">click</div>
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM