解决方法

  • 比如在执行一篇指南的代码:相同的功能可以通过使用一个适当的事件处理程序,如onBlur和聚焦事件

    1. class BlurExample extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.state = { isOpen: false };
    5. this.timeOutId = null;
    6. this.onClickHandler = this.onClickHandler.bind(this);
    7. this.onBlurHandler = this.onBlurHandler.bind(this);
    8. this.onFocusHandler = this.onFocusHandler.bind(this);
    9. }
    10. onClickHandler() {
    11. this.setState(currentState => ({
    12. isOpen: !currentState.isOpen
    13. }));
    14. }
    15. // We close the popover on the next tick by using setTimeout.
    16. // This is necessary because we need to first check if
    17. // another child of the element has received focus as
    18. // the blur event fires prior to the new focus event.
    19. onBlurHandler() {
    20. this.timeOutId = setTimeout(() => {
    21. this.setState({
    22. isOpen: false
    23. });
    24. });
    25. }
    26. // If a child receives focus, do not close the popover.
    27. onFocusHandler() {
    28. clearTimeout(this.timeOutId);
    29. }
    30. render() {
    31. // React assists us by bubbling the blur and
    32. // focus events to the parent.
    33. return (
    34. <div onBlur={this.onBlurHandler}
    35. onFocus={this.onFocusHandler}>
    36. <button onClick={this.onClickHandler}
    37. aria-haspopup="true"
    38. aria-expanded={this.state.isOpen}>
    39. Select an option
    40. </button>
    41. {this.state.isOpen ? (
    42. <ul>
    43. <li>Option 1</li>
    44. <li>Option 2</li>
    45. <li>Option 3</li>
    46. </ul>
    47. ) : null}
    48. </div>
    49. );
    50. }
    51. }

代码执行结果为空。原因:我定义了class,却没有输出它。寻找了一个有输出的,并做了相对应的修改。

  1. ReactDOM.render(<BlurExample />, document.getElementById('root'))

发现还是为空,对比了 html模块,发现没有显示 div 模块,添加了 div 模块 ,发现还是没有执行。发现是 JS 包 没有引入
image.png

引入后,输出了正确的结果。

image.png

总结

  • 如果JS 包能够在原来的项目中能够找到,直接引用就好,如果找不到,需要去 react 文档 寻找 相关的 JS 包。
  • 当定义一个类或者对象的时候,需要做一个输出以及显示模块才能看到结果。