首页 > 父组件与多个子组件之通信

父组件与多个子组件之通信

目前的问题是这样的:

一表单父组件,中有多个input输入框,然每一个input输入框是已封装好的组件,现在我的需求是想获取这多个input组件的输入值,并传入表单父组件的state中去。

我知道父组件获取子组件的数据的方式之一可以是父组件传入子组件一个自己的方法,子组件获取值之后再调用父组件传入的方法,把值作为参数传入。

但是现在有多个input子组件,要怎么处理才能把子组件的值同时传入父组件的一个方法中呢?

父组件(之前用的是表单元素input,和textarea,改成封装后的组件就不能正确获取数据了):

class Activity extends React.Component{

    constructor(){
        super();
        this.state={
            title : null, 
            brief : null
        };
    }

    handleChange(){
        this.setState({
            title : this.refs.title.value,
            brief : this.refs.brief.value
        });
    }

    render(){
        return(
                    
                <form className="activity_publish_main" action="#" method="post">
                    
                    <Input 
                        ref="title" 
                        placeholder="请输入活动标题" 
                        onChange={ this.handleChange.bind(this) }
                    />
                    
                    <Textarea 
                        ref="brief" 
                        placeholder="本活动的一两句话介绍" 
                        onChange={ this.handleChange.bind(this) } 
                    />
                
                    {/*封面上传、预览*/}
                    <ImgCrop title={ this.state.title } brief={ this.state.brief }/>
                    
                </form>
        );
    }
};

子组件:

class Input extends React.Component{

    render(){ 
        return(
            <input 
                type={ this.props.type } 
                className="input_component" 
                placeholder={ this.props.placeholder }
            />
        );
    };
};

组件

<Input 
    placeholder="请输入活动标题" 
    onChange={ (ev) => this.handleChange(ev, 'title') }
/>

方法

handleChange(ev, type){
    const { value } = ev.currentTarget;
    this.setState({
       [type] : value,
    });
}

关于react的表单这块确实很繁琐,除了楼上的onChang方法,其实还可以用一些npm包,比如redux-form,它对react的表单处理还是比较完善的,建议尝试使用以下.推荐一篇文章http://blog.csdn.net/qq_16085211/article/details/50450510


如果只是目前这个应用场景的话,我觉得 @kikong 的做法是比较好的选择。

如果真要在父子组件间传递数据的话,可以用context属性。

官网介绍

一篇blog


各个子组件在输入发生变更的时候,发送change事件
父组件监听change事件,来收集各个子组件的值
父子组件之间通过事件脱耦~

【热门文章】
【热门文章】