2016-01-03 60 views
1

在一个快速总结中,我实现的是一个photoupload系统。我有一个显示上传图片预览的div。这个div位于父组件中,我们将调用parent.jsx。在我们称之为child.jsx的子组件中,我实现了一个上传系统。将JSON对象从子组件传递到父组件

里面child.jsx我有以下代码:

const FileUpload = React.createClass({ 
render: function() { 
    return(
     <div> 
     //dropzone is essentially a file input element 
     <Dropzone multiple={false} onDrop={this._onDrop}> 
     </Dropzone> 
     </div> 
    ); 
    }, 
    _onDrop: function(files) { 
    this.setState({ 
     photo: files 
    }); 
    }, 

我想了photo对象传递到我的父文件,并在下面的div使用该条件显示它:

<div> 
    {this.state.coverPhoto.map(function(file) {return <img key={1} src={file.preview} />;})} 
</div> 

我正在考虑创建一个函数,该函数在子组件中调用时返回照片对象。也许是这样的子组件中:

returnFiles: function() { 
    return Photo 
    } 

然后在父组件可致电我FileUpload.returnFiles并设置我的状态有什么返回。有任何想法吗?

回答

1

尽管我认为调用子组件的函数具有直觉意义,但这打破了为什么React是如此优秀的工具的基本原因之一。

通过限制从父到子的数据流,React大大降低了应用程序的复杂性。

但是,就像JavaScript中的其他任何数据一样,您可以将函数传递给子代。这样,他们只在孩子的范围内被调用,但是在需要他们的地方处理。

const Parent = React.createClass({ 
    render: function() { 
    return(
     <Child onDrop={this.handleOnDrop} 
    ); 
    }, 
    handleOnDrop: function(files) { 
    this.setState({ 
     photo: files 
    }); 
    } 
} 

const Child = React.createClass({ 
    render: function() { 
    <Dropzone multiple={false} onDrop={this.props.onDrop} /> 
    } 
}) 
相关问题