2016-03-05 119 views
2

获得子组件数据我有一个反应成分象下面这样:阵营:从父

<Parent> 
    <Child /> 
    <button type="button" /> 
</Parent> 

<Child />中有一个input[type="file"]表单控件。

当我点击<Parent />按钮,我要上传的<Child />与阿贾克斯的文件,

我怎么能访问内部<Child />input[type="file"]

我尝试使用refs

<Parent> 
    <Child ref="child"/> 
    <button type="button" /> 
</Parent> 

,这样我可以通过写

this.refs.child.refs.file 

访问input,但我不认为这是最好的做法....

回答

0

在家长:

_handleImageUpload(image) { 
    this.setState({ 
    image: image 
    }); 
} 

<Child onImageUpload={this._handleImageUpload} /> 

在孩子:

_handleSubmit(e) { 
    e.preventDefault(); 
    this.props.onImageUpload(this.state.file); 
} 

_handleImageChange(e) { 
    e.preventDefault(); 
    let file = e.target.files[0]; 

    reader.onloadend =() => { 
    this.setState({ 
     file: file 
    }); 
    } 
} 

从子渲染:

<form onSubmit={this._handleSubmit}> 
    <input type="file" onChange={this._handleImageChange} /> 
    <button type="submit" onClick={this._handleSubmit}>Upload Image</button> 
</form> 
0

让你的孩子组成的 “Controlled Component”。

var Parent = React.createClass({ 
    getInitialState() { 
    inputValue: '' 
    }, 

    render() { 
    return (
     <div> 
      <Child onChange={this.onChange}></Child> 
      <button onChange={this.onSubmit} type="button" /> 
     </div> 
    ); 
    }, 

    onChange(e) { 
    this.setState({ inputValue: e.target.value }); 
    }, 

    onSubmit() { 
    //do your ajax operation with this.state.inputValue here 
    } 
}); 

var Child = React.createClass({ 
    getInitialState() { 
    inputValue: '' 
    }, 

    render() { 
    return (
     <input 
     type='file' 
     onChange={this.props.onChange} /> 
    ); 
    } 
}); 

对于详细的解释去here

+1

你的情况,你不需要'getInitialState'在'Child'组件 –