代码之家  ›  专栏  ›  技术社区  ›  KT-mongo

如何使用react中的onclick事件更改属性值

  •  0
  • KT-mongo  · 技术社区  · 7 年前

    假设以下组件:

    class App extends Component {
      constructor(props){
        super(props);
      }
    
      func1 = () => {
      ....
        }
    
      func2 = () => {
      ...
        }
    
      render() {
        return (
           <div>
              <Component
                activity={this.func1}
               />
          </div>
        );
      }
    }
    

    如何从组件函数内部实现onclick事件,以便在主应用程序中得到以下结果:

     <div>
       <Component
         activity={this.func2}
       />
     </div>
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Dhaval Chheda    7 年前

    正常流量如下

    class App extends Component {
      constructor(props){
        super(props);
      }
    
      func1 = () => {
      ....
        }
    
      func2 = () => {
      ...
        }
    
      render() {
        return (
           <div>
              <Component
                activity={this.func1}
               />
          </div>
        );
      }
    }
    
    
    <div>
       <Component
         activity={this.props.activity(arguments)}
       />
     </div>
    

    这样做将使活动属性调用父组件中定义的func1。

    注意:理想情况下,您应该调用一个函数作为事件的属性,而不仅仅是普通属性