资讯专栏INFORMATION COLUMN

React学习笔记—属性转移

fanux / 1000人阅读

摘要:我们可以使用属性延伸覆盖原来的属性值手动转移大部分情况你应该明确的向下传递属性,这样可以确保你只需要暴露内部的一个子集。但是属性属性或者属性呢利用转移使用了的结构化赋值,所以引入时要加入,如下

React当中的组件嵌套很常见,外部组件暴露的属性也许会干一些复杂的实现细节。
我们可以使用属性延伸覆盖原来的属性值

var Component = React.createClass({
    render: function () {
        return 
this is a div
} }); React.render( , document.body );
手动转移

大部分情况你应该明确的向下传递属性,这样可以确保你只需要暴露内部API的一个子集。

var FancyCheckbox = React.createClass({
  render: function() {
    var fancyClass = this.props.checked ? "FancyChecked" : "FancyUnchecked";
    return (
      
{this.props.children}
); } }); React.render( Hello world! , document.getElementById("example") );

但是name属性、title属性或者onMouseOver属性呢?

利用JSX ... 转移
var FancyCheckbox = React.createClass({
    render: function() {
        var { checked, ...other } = this.props;
        var fancyClass = checked ? "FancyChecked" : "FancyUnchecked";
        // `other` contains { onClick: console.log } but not the checked property
        return (
            
); } }); React.render( Hello world! , document.body );
  

var { checked, ...other } = this.props;使用了ES7的结构化赋值,所以引入时要加入harmony,如下:

                
阅读需要支付1元查看
<