问题
React has a few custom defined attributes. How can I define my own?
Why?
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
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() {
// ...
}
});
I’m not happy with the boilerplate code for every property. I want to copy all the passed properties except startAngle
and endAngle
.
I came up with the following 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;
}
I’d like to define copyProps
attribute.
XSLT allows to tunnel attributes:
<path d={...}>
<xsl:copy-of select="@*" />
</path>
I want something similar for React.js.
回答1:
You can use this.transferPropsTo
:
return this.transferPropsTo(<path .../>);
If you want to omit certain props, you can explicitly set them to null
, e.g.
<path startAngle={null} />
but if the component you transfer the props to doesn't have such a prop anyway, it's not really necessary to do that.
See the documentation for more information.
回答2:
Starting React v0.12, transferPropsTo are replaced by JSX Spread Attributes:
return <path {...this.props}/>
来源:https://stackoverflow.com/questions/22852422/react-js-defining-custom-attributes