19

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

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

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

3 回答 3

43

选项1:

使用arrow functions(与 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:

在构造函数中使用绑定

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

       handleClick() {
          // handle click
       }

       render() {

         return (
           <div onClick={this.handleClick}>
             .....
           </div>
         )
       }
     }
于 2016-11-23T20:21:08.457 回答
8

我建议您在类构造函数中使用绑定。这将避免内联重复(和混淆),并且只会执行一次“绑定”(当组件启动时)。

这是一个如何在用例中实现更简洁 JSX 的示例:

class YourComponent extends React.Component {
    constructor(props) {
        super(props);

        // Bind functions
        this.handleClick = this.handleClick.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleClick() {
        this.onClick('someString');
    }
    onClick(param) {
        // That's your 'onClick' function
        // param = 'someString'
    }

    handleSubmit() {
        // Same here.
        this.handleFormSubmit();
    }
    handleFormSubmit() {
        // That's your 'handleFormSubmit' function
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <p>...</p>
                <button onClick={this.handleClick} type="button">Cancel</button>
                <button type="submit">Go!</button>
            </form>
        );
    }
}
于 2016-11-23T22:17:00.723 回答
2

尽管之前的所有答案都可以达到预期的结果,但我认为下面的片段值得一提。

class myComponent extends PureComponent {

  handleOnclickWithArgs = arg => {...};

  handleOnclickWithoutArgs = () => {...};

  render() {
    const submitArg = () => this.handleOnclickWithArgs(arg);
    const btnProps = { onClick: submitArg }; // or onClick={submitArg} will do

    return (
      <Fragment>
        <button {...btnProps}>button with argument</button>
        <button onClick={this.handleOnclickWithoutArgs}>
          button without argument
        </button>
     </Fragment>
   );
  }
}

于 2018-05-26T09:24:47.643 回答