2016-03-05 120 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'組件 –