[英]React.js — How to pass properties object to child component?
I have a component called tileGroup
that has a property that is a collection(array) of other properties. 我有一个名为
tileGroup
的组件,它具有一个属性,该属性是其他属性的集合(数组)。
The parent component( tileGroup
) renders a list of child components by using each set of properties in the collection to create a new component. 父组件(
tileGroup
)通过使用集合中的每组属性来创建新组件,从而呈现子组件的列表。
Right now I am individually mapping each property from the set to the child component but this will become cumbersome if the property count for a component increases and I'm sure there is a cleaner, simpler way to do it... 现在我将每个属性从集合映射到子组件,但如果组件的属性数量增加,这将变得很麻烦,我确信有更简洁的方法来做...
How can I pass the full set of properties on to the child component without remapping each property? 如何在不重新映射每个属性的情况下将完整的属性集传递给子组件?
Example code: 示例代码:
tileGroupData = {someProperty: 'something', someOtherProperty:'something',
tiles: [{vsize:1, hsize:2, etc...}, {vsize:2,hsize:3,title:'whatever'}]};
and then component creation.. 然后组件创建..
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}/>;
});
Apparently transferPropsTo is being deprecated. 显然,transferPropsTo已被弃用。 With recent versions of React you can use JSX spread attributes:
使用最新版本的React,您可以使用JSX传播属性:
return <tileSimple {...tile} />;
More info about this here: Deprecating transferPropsTo 有关这方面的更多信息: Deprecating transferPropsTo
For those use cases, the easiest thing is to fallback to the JS API instead of JSX. 对于这些用例,最简单的方法是回退到JS API而不是JSX。
return tileSimple(tile);
To understand why it works, look at the generated version of the version you want using the JSX Compiler tool ( http://facebook.github.io/react/jsx-compiler.html ) 要了解它的工作原理,请使用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});
实际上,您可以在渲染中执行以下操作
return this.transferPropsTo(<tileSimple />);
What you propose doing, 你建议做什么,
return <tileSimple allTheProps={tile} />;
works just fine. 工作得很好。
Within the tileSimple
component you should then be able to access the properties using syntax like, 在
tileSimple
组件中,您应该能够使用如下语法访问属性:
var vsize = this.props.allTheProps.vsize;
var hsize = this.props.allTheProps.hsize;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.