加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React学习笔记—属性转移

发布时间:2020-12-15 04:52:15 所属栏目:百科 来源:网络整理
导读:React当中的组件嵌套很常见,外部组件暴露的属性也许会干一些复杂的实现细节。 我们可以使用属性延伸覆盖原来的属性值 var Component = React.createClass({ render: function () { return div {...this.props} title="zzz"this is a div/div }});React.rend

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读