javascript - 在 react 中创建受控输入

标签 javascript reactjs

我是一名新手,正在通过 FreeCodeCamp 学习 React。关于这个挑战,它说:

When you type in the input box, that text is processed by the handleChange() method, set as the input property in the local state, and rendered as the value in the input box on the page. The component state is the single source of truth regarding the input data.

我写了这个解决方案:

 class ControlledInput extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    input: ''
  };
  // Change code below this line
  this.handleChange = this.handleChange.bind(this);
  // Change code above this line
}
// Change code below this line
handleChange(event) {
  this.setState({
    input: event.target.value
  })
}
// Change code above this line
render() {
  return (
    <div>
      { /* Change code below this line */}
      <input value={this.state.input} onChange={this.handleChange()} />
      { /* Change code above this line */}
      <h4>Controlled Input:</h4>
      <p>{this.state.input}</p>
    </div>
  );
}
};

控制台显示:

“Build error, open your browser console to learn more.”

我哪里做错了?我看不到我的错误..

最佳答案

该问题与您如何将事件处理程序分配给 onChange 有关。

onChange 需要一个回调函数,当输入值更改时将触发该函数。在您的帖子中使用 onChange={this.handleChange()} 时,您实际上将 undefined 分配给 onChange,因为 handleChange函数更新组件状态但它不返回任何内容。

将其更改为 onChange={this.handleChange} 即可达到您期望的效果。当输入更改时,将调用 this.handleChange 并将 event 对象作为参数传入。

希望有帮助。

关于javascript - 在 react 中创建受控输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65281728/

相关文章:

reactjs - 如何在 react 大日历中获取月 View 中周的全日名称

javascript - 添加新消息时自动向下滚动

javascript - 是什么让 Date 构造函数接受 momentjs 对象?

javascript - 如何使用 javascript 立即清晰地播放音频而没有任何延迟?

javascript - 使用 JavaScript 从 json 对象中删除特定数据

javascript - 为什么这个基本的 react-beautiful-dnd 示例没有动画

javascript - 混淆模拟无状态 React 组件辅助函数与 sinon、enyzme 和 ES6 导入

javascript - 由于类型不匹配,Firefox 阻止了资源

javascript - 如何在 Next.js 中访问 getServerSideProps 中的路由参数?

reactjs - Material-UI CSV/PDF 打印导出无法使用 "@mui/x-data-grid"模块