React学习笔记—属性转移

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

var Component = React.createClass({
    render: function () {
        return <div {...this.props} title="zzz">this is a div</div>
    }
});

React.render(
    <Component name="xxx" title="yyy"/>,
    document.body
);

手动转移

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

var FancyCheckbox = React.createClass({
  render: function() {
    var fancyClass = this.props.checked ? 'FancyChecked' : 'FancyUnchecked';
    return (
      <div className={fancyClass} onClick={this.props.onClick}>
        {this.props.children}
      </div>
    );
  }
});
React.render(
  <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
    Hello world!
  </FancyCheckbox>,
  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 (
            <div {...other} className={fancyClass} />
        );
    }
});
React.render(
    <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
        Hello world!
    </FancyCheckbox>,
    document.body
);

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

<script type="text/jsx;harmony=true">
    原文作者:小俞
    原文地址: https://segmentfault.com/a/1190000002671045
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞