JSX道具不应该使用.bind()

时间:2016-11-23 20:02:33

标签: reactjs react-jsx jsx function-binding

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

    {this.onClick.bind(this, 'someString')}>
and
     <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>

3 个答案:

答案 0 :(得分:23)

选项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>
         )
       }
     }

答案 1 :(得分:5)

我建议你在类构造函数中使用绑定。这将避免内联重复(和混乱)并将执行&#34; bind&#34;只有一次(启动组件时)。

以下是一个如何在用例中实现更清晰的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>
        );
    }
}

答案 2 :(得分:0)

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

&#13;
&#13;
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>
   );
  }
}
&#13;
&#13;
&#13;