首页 > 解决方案 > React - jQuery - 在文档加载时添加 onClick 监听器

问题描述

我需要在文档加载时添加一个 onClick 侦听器。由于几个原因,我不想使用 state 来做到这一点。首先,我想创建一个可以在任何地方使用并始终显示下一个元素的规则。其次,我还想添加淡入淡出或幻灯片效果。下面的代码不起作用。

componentDidMount() {
  $(document).ready(function() {
    $(".showNext").click(function() {
      $(this).next().slideToggle();
    });
  });
}

if (!loadingData)
  render() {
    return(
      <div>

        <div className="showNext">Show element #1</div>
        <div style={{display:"none"}}>Element #1</div>

        <div className="showNext">Show element #2</div>
        <div style={{display:"none"}}>Element #2</div>

      </div>
    );
  }
} else {
  <div>Loading ... </div>
}

标签: jqueryreactjs

解决方案


如果您已经在使用该componentDidMount方法,那么您似乎并不关心创建任何函数,请使用以下代码更新您的代码:

handleClickMethod = () => console.log('clicked')
render() {
  return(
    <div>

      <div className="showNext">Show element #1</div>
      <div style={{display:"none"}} onClick={this.handleClickMethod}>Element #1</div>

      <div className="showNext">Show element #2</div>
      <div style={{display:"none"}} onClick={this.handleClickMethod}>Element #2</div>

    </div>
  );
}

甚至更好!创建一个可点击的组件!

class Clickable extends Component {
  _handleClick = () => {
    console.log('clicked')
    this.props.onClick && this.props.onClick()
  }

  render() {
    const {...props} = this.props
    return <div {...props} onClick={this._handleClick}/>
  }
}

并在您的主要组件中像这样使用它:

render() {
  return(
    <div>

      <Clickable className="showNext">Show element #1</Clickable>
      <div style={{display:"none"}}>Element #1</div>

      <Clickable className="showNext">Show element #2</Clickable>
      <div style={{display:"none"}}>Element #2</div>

    </div>
  );
}

无论如何,对于你想要完成的事情,你会更好地使用更像这样的东西:

class Toggleable extends Component {
  state = {toggled: false}

  _toggleDiv = () => {
    this.setState({toggled: !this.state.toggled})
  }

  render() {
    return (
      <div>
        <div className="showNext" onClick={this._toggleDiv}>{this.props.showText}</div>
        {this.state.toggled && <div>{this.props.text}</div>}
      </div>
    )
  }
}

并在您的主要组件中像这样使用它:

render() {
  return(
    <div>

      <Toggleable showText={'Show element #1'} text={'Element #1'}/>
      <Toggleable showText={'Show element #2'} text={'Element #2'}/>

    </div>
  );
}

欢迎来到模块化编程!


推荐阅读