React.js: Defining custom attributes

吃可爱长大的小学妹 提交于 2019-12-11 10:22:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!