reactjs - JSX Prop 不应使用 .bind()

标签 reactjs jsx function-binding

当我以这种方式进行绑定(bind)时如何修复此错误:以前在构造函数中的绑定(bind)已解决,但这对我来说有点复杂:

{this.onClick.bind(this, 'someString')}>

<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>

最佳答案

选项 1:

使用箭头函数(使用 babel-plugins) PS:- 实验性功能

class MyComponent extends Component {
   handleClick = (args) => () => {
      // access args here;
      // handle the click event
   }

   render() {
     return (
       <div onClick={this.handleClick(args)}>
         .....
       </div>
     )
   }
 }

选项 2:不推荐

在渲染中定义箭头函数

   class MyComponent extends Component {
       render() {
         const handleClick = () => {
          // handle the click event
         }
         return (
           <div onClick={handleClick}>
             .....
           </div>
         )
       }
     }

选项 3:

在构造函数中使用绑定(bind)

   class MyComponent extends Component {
       constructor() {
         super();
         this.handleClick = this.handleClick.bind(this);
       }

       handleClick() {
          // handle click
       }

       render() {

         return (
           <div onClick={this.handleClick}>
             .....
           </div>
         )
       }
     }

关于reactjs - JSX Prop 不应使用 .bind(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40773220/

相关文章:

javascript - 寻找简单地将 jsx 转换为标记字符串的自定义 JSX babel 插件

javascript - React 组件返回原始 HTML

javascript - 如何在变量中缓存 HTMLElement.focus?

javascript - 使用最初 undefined variable 的属性来实现 useEffect 依赖

javascript - 将网络摄像头视频渲染到 Canvas 时超出最大调用堆栈大小

javascript - react /ES6 : Arrow Function not binding "this" as expected

reactjs - 将额外的 props 传递给 FieldArray 中包装的组件 (React)

javascript - TypeError : e. _panGestureHandler.current.setNativeProps 不是函数