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">

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...