React dynamically adds onClick click event and dynamically adds hover style

1. Dynamically add the onClick click event in the React class component according to the value of the flag:

When the flag is true, an object containing the onClick attribute is returned, and the attribute value is an arrow function, and then the ES6 expansion operator is used to expand the object;

2. In the React class component, the hover style is dynamically added according to the value of the flag: two events, onMouseOver and onMouseLeave, are used. When the mouse moves into the element, onMouseOver is triggered to execute. The value of isHover is set to true. The textDecoration style value is 'underline'.

<div
  {...(this.state.flag ? {
    onClick: () => console.log('点击事件'),
    onMouseOver: () => this.setState({ isHover: true }),
    onMouseLeave: () => this.setState({ isHover: false }),
  } : {})
  }
  style={
   
   {
    cursor: this.state.flag ? 'pointer' : 'default',
    textDecoration: this.state.flag && this.state.isHover ? 'underline' : 'auto'
  }}
  >
  文本
</div>

Guess you like

Origin blog.csdn.net/u010234868/article/details/131475385