子组件向父组件传参(不用redux)?

好比antd里的RadioGroup和Radio

<RadioGroup onChange={this.onChange} value={this.state.value}>
   <Radio value={1}>A</Radio>
   <Radio value={2}>B</Radio>
   <Radio value={3}>C</Radio>
   <Radio value={4}>D</Radio>
</RadioGroup>

是如何做到点击Radio的时候触发了onChange呢?

阅读 3.4k
4 个回答

这个东西看下源码就知道了 通过Context传递

Group:

static childContextTypes = {
    radioGroup: PropTypes.any,
};

getChildContext() {
    return {
      radioGroup: {
        onChange: this.onRadioChange,//内部调用了this.props.onChange
      },
    };
  }

Radio:

static contextTypes = {
    radioGroup: PropTypes.any,
};
render(){
    //这里就获取到onChange事件了
    radioProps.onChange = this.context.radioGroup.onChange;
}

看了一下antd的源码,Radio.Group里面设置context,

    static childContextTypes: {
        radioGroup: PropTypes.Requireable<any>;
    };
    constructor(props: RadioGroupProps);
    getChildContext(): {
        radioGroup: {
            onChange: (ev: RadioChangeEvent) => void;
            value: any;
            disabled: boolean | undefined;
            name: string | undefined;
        };
    };

然后Radio里面获取context,在值更改的时候调用Radio.Group的onChange

var props = this.props,
    context = this.context;

var prefixCls = props.prefixCls,
    className = props.className,
    children = props.children,
    style = props.style,
    restProps = __rest(props, ["prefixCls", "className", "children", "style"]);

var radioGroup = context.radioGroup;

var radioProps = (0, _extends3['default'])({}, restProps);
if (radioGroup) {
    radioProps.name = radioGroup.name;
    radioProps.onChange = radioGroup.onChange;
    radioProps.checked = props.value === radioGroup.value;
    radioProps.disabled = props.disabled || radioGroup.disabled;
}
var wrapperClassString = (0, _classnames2['default'])(className, (_classNames = {}, (0, _defineProperty3['default'])(_classNames, prefixCls + '-wrapper', true), (0, _defineProperty3['default'])(_classNames, prefixCls + '-wrapper-checked', radioProps.checked), (0, _defineProperty3['default'])(_classNames, prefixCls + '-wrapper-disabled', radioProps.disabled), _classNames));
return React.createElement(
    'label',
    { className: wrapperClassString, style: style, onMouseEnter: props.onMouseEnter, onMouseLeave: props.onMouseLeave },
    React.createElement(_rcCheckbox2['default'], (0, _extends3['default'])({}, radioProps, { prefixCls: prefixCls, ref: this.saveCheckbox })),
    children !== undefined ? React.createElement(
        'span',
        null,
        children
    ) : null
);

react中子组件向父组件发消息方式:子组件触发父组件传递下来的props中指定的方法

把父组建的onchange当作参数传递给子组件,然后在子组件的时间处理中调用父组件的onchange

顺便python教程

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题