代码之家  ›  专栏  ›  技术社区  ›  wake-0

reactjs向子组件添加回调函数

  •  1
  • wake-0  · 技术社区  · 7 年前

    我想将回调附加到已经创建的react组件,这是可能的吗?

    这是我的包装类,我想调用 callbackToCall 从现有子项:

    import React from 'react';
    class MyComponent extends React.Component {
    
        callbackToCall() {
            console.log("callback called.");
        }    
    
        render() {
            const {children} = this.props;
            // Here I want to attach the callback to call
            // E.g. children.props.callback = callbackToCall;
            return (
            <div>
                MyStuff
                {children};
            </div>
            ); 
        }
    }
    

    子类,它没有对容器类的任何回调:

    import React from 'react';
    class Child extends React.Component {
    
        render() {
            return <button onClick={this.props.callback}>Click me</button>
        }
    }
    

    这是组件的调用,这里我不知道如何引用回调:

    <MyComponent>
        <Child /* Here I cannot set the callback callback={...callbackToCall}*/ />
    </MyComponent>
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Estus Flask    7 年前

    鉴于 MyComponent 是接受唯一子级并应提供 callback 支持它,它应该是:

    class MyComponent extends React.Component {
        ...
        render() {
            const child = React.cloneElement(
              React.Children.only(this.props.children),
              { callback: this.callbackToCall }
            );
    
            return (
              <div>
                MyStuff
                {child};
              </div>
            ); 
        }
    }
    

    或者, 肌力成分 可提供 成分 而不是 要素 通过道具,比如:

    class MyComponent extends React.Component {
        ...
        render() {
            return (
              <div>
                MyStuff
                <this.props.component callback={this.callbackToCall}/>
                {this.props.children};
              </div>
            ); 
        }
    }
    

    这种方式 肌力成分 还可以接受儿童用于其他目的,如 <MyComponent component={Child}>...</MyComponent> .

        2
  •  -1
  •   gatata    7 年前

    react.js 文档,

    你可以试试这个 您需要调用构造函数和super来初始化状态或绑定方法。 否则,this.props将返回未定义。

    import React from 'react';
    class MyComponent extends React.Component {
    
    constructor(props){
      super(props);
      this.callbackToCall = this.callbackToCall.bind(this);
    }
    
    callbackToCall() {
        console.log("callback called.");
    }    
    
    render() {
        const {children} = this.props;
    
    
        // Call the function using
        {this.callbackToCall}
    
        return (
        <div>
            MyStuff
            {children};
        </div>
        ); 
    }
    }
    

    确保将函数作为引用传递,如this.CallbackToCall而不是this.CallbackToCall() 希望这有帮助