javascript React.js:将事件从父级附加到子级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29412738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:29:46  来源:igfitidea点击:

React.js: attach event from parent to children

javascriptreactjs

提问by pistacchio

as shown in the example below, I'd like MyComponent to dynamically attach an "onClick" event to its children. The onClick event should fire alertView that should be able to call the clicked element method "getValue".

如下例所示,我希望 MyComponent 动态地将“onClick”事件附加到其子项。onClick 事件应该触发应该能够调用被点击元素方法“getValue”的 alertView。

JSFiddle: http://jsfiddle.net/2g638bp8/

JSFiddle:http: //jsfiddle.net/2g638bp8/

How to do this? Thanks

这个怎么做?谢谢

var MyComponent = React.createClass({
    alertValue: function () {
        // RETRIEVE THE CHILD HERE
        alert(child.getValue());
    },
    render: function () {
        var children = React.Children.map(this.props.children, function (c, index) {
            return React.addons.cloneWithProps(c, {
                ref: 'child-' + index
            });
        });
        return (
            <div>
                {children}
            </div>
        );
    }
});

var MySubComponent = React.createClass({
    getValue: function () {
        return this.props.val;
    },
    render: function () {
        return (
            <div>{this.props.val}</div>
        );
    }
});

React.render(
    <div>
        <MyComponent>
            <MySubComponent val="1" />
            <MySubComponent val="2" />
            <MySubComponent val="3" />
        </MyComponent>
    </div>,
    document.getElementById('container')
);

回答by WiredPrairie

You can't call methods on child components in React. You can only set properties. (The childis actually a ReactElementwhich contains information about the class and associated properties. It is not an instance of the component you created).

你不能在 React 中调用子组件的方法。您只能设置属性。(child实际上是 a ReactElement,其中包含有关类和相关属性的信息。它不是您创建的组件的实例)。

So, you could think about this a slightly differentway and move the onClickto the MySubComponent:

所以,你可以想想这一个稍微不同的方式,并移动onClickMySubComponent

var MyComponent = React.createClass({
    onHandleGiveValue: function (value) {
        alert(value);
    },
    render: function () {
        const children = React.Children.map(this.props.children, child => React.cloneElement(child, { onGiveValue: this.onHandleGiveValue.bind(this) }));
        return (
            <div>
                {children}
            </div>
        );
    }
});

var MySubComponent = React.createClass({
    handleClick: function() {
        this.props.onGiveValue(this.props.val);
    },
    getValue: function () {
        return this.props.val;
    },
    render: function () {
        return (
            <div onClick={ this.handleClick } >{this.props.val}</div>
        );
    }
});

React.render(
    <div>
        <MyComponent>
            <MySubComponent val="1" />
            <MySubComponent val="2" />
            <MySubComponent val="3" />
        </MyComponent>
    </div>,
    document.getElementById('container')
);

By doing that, your code can pass the current value as an event to the parent component. I've created a new event from the MySubComponentclass named onGiveValue. That for now just passes the value from this.props.val. But, it could of course be anything.

通过这样做,您的代码可以将当前值作为事件传递给父组件。我从MySubComponent名为onGiveValue. 现在只是将值从this.props.val. 但是,它当然可以是任何东西。

回答by IcyBright

  1. Pass the parent callback to the subComponent, one dont need a reference for the child component.
  2. React prefers composition design pattern, So your parent component should contains those three subComponent. JS Fiddle: http://jsfiddle.net/68vt3umg/

    var MyComponent = React.createClass({
    handleChildClick: function (e, childValue) {
       alert(childValue);
    },
    render: function () {
        return (
            <div>
              <MySubComponent val="1" onSubClicked={this.handleChildClick}/>
              <MySubComponent val="2" onSubClicked={this.handleChildClick}/>
            </div>
        );
    }});
    
    var MySubComponent = React.createClass({
      getValue: function () {
        return this.props.val;
      },
      handleOnClick: function (e, value) {
        this.props.onSubClicked(e, this.props.val);
      },
      render: function () {
        return (
            <div onClick={this.handleOnClick}>{this.props.val}</div>
        );
      }
    });
    
    React.render(
      <div>
        <MyComponent />
      </div>,
      document.getElementById('container')
    );
    
  1. 将父回调传递给子组件,子组件不需要引用。
  2. React 更喜欢组合设计模式,所以你的父组件应该包含这三个子组件。JS小提琴:http: //jsfiddle.net/68vt3umg/

    var MyComponent = React.createClass({
    handleChildClick: function (e, childValue) {
       alert(childValue);
    },
    render: function () {
        return (
            <div>
              <MySubComponent val="1" onSubClicked={this.handleChildClick}/>
              <MySubComponent val="2" onSubClicked={this.handleChildClick}/>
            </div>
        );
    }});
    
    var MySubComponent = React.createClass({
      getValue: function () {
        return this.props.val;
      },
      handleOnClick: function (e, value) {
        this.props.onSubClicked(e, this.props.val);
      },
      render: function () {
        return (
            <div onClick={this.handleOnClick}>{this.props.val}</div>
        );
      }
    });
    
    React.render(
      <div>
        <MyComponent />
      </div>,
      document.getElementById('container')
    );