React.js - 如何将属性对象传递给子组件?

Mat*_*can 71 javascript properties parent-child reactjs

我有一个名为的组件tileGroup,其属性是其他属性的集合(数组).

父组件(tileGroup)通过使用集合中的每组属性来创建子组件列表以创建新组件.

现在我将每个属性从集合映射到子组件,但如果组件的属性数量增加,这将变得很麻烦,我确信有更简洁的方法来做...

如何在不重新映射每个属性的情况下将完整的属性集传递给子组件?

示例代码:

tileGroupData = {someProperty: 'something', someOtherProperty:'something', 
                tiles: [{vsize:1, hsize:2, etc...}, {vsize:2,hsize:3,title:'whatever'}]};
Run Code Online (Sandbox Code Playgroud)

然后组件创建..

var tileGroup = React.createClass({
    render: function() {
       var thechildren = this.props.tiles.map(function(tile)
       {
           //this is what I DON'T want to be doing. 
           return <tileSimple vsize = {tile.vsize} hsize = {tile.hsize} content = {tile.content}/>;

           //what I DO want to be doing
           return <tileSimple allTheProps = {tile}/>; 
       });
Run Code Online (Sandbox Code Playgroud)

act*_*imp 127

显然,transferPropsTo已被弃用.使用最新版本的React,您可以使用JSX传播属性:

return <tileSimple {...tile} />;
Run Code Online (Sandbox Code Playgroud)

有关这方面的更多信息:https: //gist.github.com/sebmarkbage/a6e220b7097eb3c79ab7

  • @ryanpcmcquen是的.https://zhenyong.github.io/react/docs/transferring-props.html (2认同)

Vje*_*eux 32

对于这些用例,最简单的方法是回退到JS API而不是JSX.

return tileSimple(tile);
Run Code Online (Sandbox Code Playgroud)

要了解它的工作原理,请使用JSX编译器工具(http://facebook.github.io/react/jsx-compiler.html)查看所需版本的生成版本.

<tileSimple vsize = {tile.vsize} hsize = {tile.hsize} content = {tile.content}/>;
tileSimple( {vsize:  tile.vsize, hsize:  tile.hsize, content:  tile.content});
Run Code Online (Sandbox Code Playgroud)


小智 6

实际上,您可以在渲染中执行以下操作

return this.transferPropsTo(<tileSimple />);
Run Code Online (Sandbox Code Playgroud)