React.js:定义自定义属性 [英] React.js: Defining custom attributes
问题描述
反应具有一些自定义的属性。我怎么定义自己的?
React has a few custom defined attributes. How can I define my own?
我有一个 Arc
组件,下面是一些用法示例:
I have an Arc
component, a few usage examples below:
<Arc startAngle="90" endAngle="270" stroke="hsl(38, 100%, 50%)" strokeWidth="0.5" />
<Arc startAngle="45" endAngle="90" fill="hsla(38, 100%, 50%, 0.2)" />
<Arc startAngle="0" endAngle="45" className="pie-slice" />
startAngle
和 endAngle
属性是必需的。其他所有道具都是DOM属性,我只是代理到根节点。
startAngle
and endAngle
attributes are required. All the other props are DOM properties that I just "proxy" to the root node.
var Arc = React.createClass({
render: function() {
return <path d={this.calcPath()}
stroke={this.props.stroke}
strokeWidth={this.props.strokeWidth}
fill={this.props.fill}
className={this.props.className}
/>
},
calcPath() {
// ...
}
});
我对每个物业的样板代码不满意。我想复制所有传递的属性,除了 startAngle
和 endAngle
。
I’m not happy with the boilerplate code for every property. I want to copy all the passed properties except startAngle
and endAngle
.
我想出了以下API:
var Arc = React.createClass({
PROPS: {startAngle: true, endAngle: true},
render: function() {
return <path d={this.calcPath()} copyProps={cloneShallow(this.props, this.PROPS)}/>
}
});
function cloneShallow(obj, exclude) {
var result = {};
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!exclude.hasOwnProperty(key)) {
result[key] = obj[key];
}
}
return result;
}
我想定义 copyProps
属性。
XSLT允许隧道属性:
XSLT allows to tunnel attributes:
<path d={...}>
<xsl:copy-of select="@*" />
</path>
我想要类似React.js的东西。
I want something similar for React.js.
推荐答案
启动React v0.12, transferPropsTo
替换为JSX Spread属性:
Starting React v0.12, transferPropsTo
are replaced by JSX Spread Attributes:
return <path {...this.props}/>
这篇关于React.js:定义自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!