react中props和state属性

1.props,通过this.props我们可以拿到组件使用时的属性。

var HelloWorld = React.createClass({
    render: function () {
        return (
            <div data-title={this.props.title}>{this.props.content}</div>
        )
    }
});

React.render(
    <HelloWorld title="this is title" content="this is content"/>,
    document.body
);

2.获取子节点的属性 this.props.children

var HelloWorld = React.createClass({
    render: function () {
        return (
            <div>
            {
                this.props.children.map(function (child) {
                        return child;
                })}
            </div>
        )
    }
});

React.render(
    <HelloWorld title="this is title">
        <span>1</span>
        <span>2</span>
    </HelloWorld>,
    document.body
);
3.state 是同UI交互最重要的属性

var ColorButton = React.createClass({
    getInitialState: function () {
        return {bColor: 'green'};
    },
    render: function () {
        return (
            <button onClick={this.handleClick} style={{backgroundColor: this.state.bColor}}>click</button>
        )
    },
    handleClick: function (event) {
        this.setState({bColor: this.state.bColor === 'green' ? 'red' : 'green'});
    }
});

React.render(
    <ColorButton />,
    document.body
);

4.自动绑定

所有的事件处理函数当中的this指向组件的实例。如果想要拿到当前操作的DOM,通过参数event获取。

var ColorButton = React.createClass({
    getInitialState: function () {
        return {name: 'button'};
    },
    render: function () {
        return (
            <button onClick={this.handleClick}>click</button>
        )
    },
    handleClick: function (event) {
        console.log(this.state);
        console.log(event.target);
    }
});

React.render(
    <ColorButton />,
    document.body
)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值