使用循环构造将道具添加到 React 渲染调用
Add props to React render call with looping construct
假设我有一个数组 ("props"),我想用它来渲染 React 组件。类似于:
const props = [];
ReactDOM.render(<Comp prop0={props[0]} prop1={props[1]/>, document.getElementById('foo'));
是否有可以接受的方法来使用一些循环结构而不是 "hardcoding" 将 props 添加到 React 组件?
通常,您会在此处使用展开运算符:
var props = {};
props.foo = 'something';
props.bar = 'something else';
ReactDOM.render(<Component {...props} />, someDomElement);
我想如果你想渲染可变数量的 children 和可变数量的道具,你可以这样做:
const React = require('react');
module.exports = function(children){
return React.createClass({
renderChildren: function(){
return children.map(function(Child){
return (
<div>
<Child {...Child.propz}/>
</div>
)
});
},
render: function(){
return (
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>Title</title>
</head>
<body>
<div>
{this.renderChildren()}
</div>
</body>
</html>
)
}
});
};
假设我有一个数组 ("props"),我想用它来渲染 React 组件。类似于:
const props = [];
ReactDOM.render(<Comp prop0={props[0]} prop1={props[1]/>, document.getElementById('foo'));
是否有可以接受的方法来使用一些循环结构而不是 "hardcoding" 将 props 添加到 React 组件?
通常,您会在此处使用展开运算符:
var props = {};
props.foo = 'something';
props.bar = 'something else';
ReactDOM.render(<Component {...props} />, someDomElement);
我想如果你想渲染可变数量的 children 和可变数量的道具,你可以这样做:
const React = require('react');
module.exports = function(children){
return React.createClass({
renderChildren: function(){
return children.map(function(Child){
return (
<div>
<Child {...Child.propz}/>
</div>
)
});
},
render: function(){
return (
<html lang="en">
<head>
<meta charset="UTF-8"></meta>
<title>Title</title>
</head>
<body>
<div>
{this.renderChildren()}
</div>
</body>
</html>
)
}
});
};