有没有办法在 React 的 componentDidMount 方法中使用事件对象?

Is there any way to use event object inside React's componentDidMount method?

我有两个组件,App 组件和 SearchBar 组件。 SearchBar 组件是一个功能组件,表单提交由一个名为 handleSubmit 的方法处理,该方法定义在 App 组件中,并通过 props 向下传递。在 App 组件中定义的 handleSubmit 方法首先阻止浏览器表单提交的默认行为,然后异步调用 YouTube API。 API 调用总是成功的,并且每当我通过表单搜索某些内容时都有效,例如“bulidings”。但我想在组件首次呈现时显示一些默认视频,例如“游戏”。于是调用了componentDidMount中的handleSubmit方法,报错“Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'preventDefault')”。有什么方法可以在 componentDidMount 中使用事件对象吗?

这是我的代码:

应用程序:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: "",
      videos: [],
      selectedVideo: null,
    };  }


  componentDidMount() {
    this.handleSubmit("games");
  }

  // handle form submission
  handleSubmit = async (query, e) => {
    e.preventDefault();

   // API call
  };

    // handle change in input
  onIputChange = (e) => {
    const inputValue = e.target.value;
    this.setState({ inputValue });
  };

    render() {
    const inputValue = this.state.inputValue;
    return (
        <div>
          <SearhBar
            handleSubmit={(e) => this.handleSubmit(inputValue, e)}
            inputValue={inputValue}
            onInputChange={this.onIputChange}
          />
        </div>
    );
  }

搜索栏:

function SearhBar(props) {
  return (
    <form onSubmit={props.handleSubmit}>
      <label>Search Video</label>
      <input
        onChange={props.onInputChange}
        type="text"
        value={props.inputValue}
      />
    </form>
  );
}

不,你不能,因为你在那里没有活动......你可以做两件事:

  • if (e) e.preventDefault()
  • 包围 e.preventDefault
  • 将公共 callApi 部分提取到方法中并从 componentDidMount:
  • 中调用该方法
  // handle form submission
  handleSubmit = async (query, e) => {
    e.preventDefault();

    this.callApi(query)
  };
  componentDidMount() {
    this.callApi("games");
  }

  callApi(query) {
    // code to call api
  }