【问题标题】:Reactjs possible to change onclick function name like changing propsReactjs 可以像更改道具一样更改 onclick 函数名称
【发布时间】:2016-03-15 21:44:02
【问题描述】:

可以改变onclick功能,比如改变props,比如把'props message'改成'new message'?

例如:

var SmallMessageBox = React.createClass({

  getDefaultProps: function() {
    return {
      message: 'props message',
      onClick: 'this.eventHandler_Two'
    }
  },

  eventHandler_One: function(){
    console.log('event1');
  },

  eventHandler_Two: function(){
    console.log('event2');
  },

  render: function(){

    return (
      <div>
        <small>{this.props.message}</small>
        <button onClick={this.eventHandler_One}>button</button>
      </div>  
    );
  }
});

React.render(
  <SmallMessageBox message="new message" onClick="new onClick function for event2" />, document.getElementById('react-container'),
  function(){
    console.log('after render');
  }
);

【问题讨论】:

    标签: javascript function reactjs


    【解决方案1】:

    是的,可以为组件提供函数类型的属性。在执行 prop 函数之前,您可以将事件处理程序直接绑定到通过 props 传递的函数,或者在内部组件方法中执行某些操作。请注意,您不能更改所提供函数的定义,一旦目标组件被初始化,它将不会被更新。

    此外,在许多情况下,您必须在传入的函数上使用绑定来维护正确的上下文。

    根据您的示例,它应该是这样的:

    var SmallMessageBox = React.createClass({
    
    
    
      propTypes: {
        message: React.PropTypes.string.isRequired,
        onClick: React.PropTypes.func
      },
    
      getDefaultProps: function() {
        return {
          message: 'props message',
          onClick: function() {
            console.log("I will be executed, only if props.onClick was not specified");
          }
        }
      },
    
      eventHandler: function() {
    
      },
    
      render: function() {
    
        return (
          <div>
            <small>{this.props.message}</small>
            <button onClick={ this.props.onClick }>button</button>
          </div>  
        );
      }
    });
    
    React.render(
      <SmallMessageBox onClick={function() { console.log( "remove me to get the other console.log"); }} message="new message"/>, document.getElementById('react-container'),
      function(){
        console.log('after render');
      }
    );
    

    我还鼓励您隐式指定您的道具及其类型。您可以找到更多信息here。

    【讨论】:

    • 谢谢,嗯,我没有得到控制台日志,当我点击时,你知道吗?
    • 是的,return { onClick: this.eventHandler } this 指向包装对象而不是组件。只需将其分配给 getDefaultProps 中的变量上下文,然后引用它:onClick: context.eventHandler。为了方便起见,我更新了答案中的示例。
    • jsbin.com/cayogumegu/1/edit?html,js,console,output 你能在这里试试,试图获取控制台日志消息 :) 吗?
    • 更新了 JSbin。由于一些我不知道的奇怪原因,getDefaultProps 不能很好地引用this。我使用 ES6 语法并在构造函数中定义组件,而不是使用 createComponent 创建实例,并且在那里没有这个问题。如果您内联定义函数,则按预期工作。
    猜你喜欢
    • 2019-07-27
    • 2019-06-02
    • 2014-10-07
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多